Javascript承诺将param传递给对象

时间:2017-01-01 12:57:18

标签: javascript jquery

var getData = new Promise(function(resolve, reject){
    $.post( "data.php", { search: inputData }, function( data ) { //need to pass this
        data = $.parseJSON(data);
    });

    if (data) {
        resolve(data);
    }
});

this.inputText.on('keyup', function(){
    var inputData = this.value; //I need to pass this into object

    getData.then(function(fromResolve){

        console.log(fromResolve);

    }).catch(function(fromReject){

        console.log(fromReject);

    });
});

我有一个jQuery ajax帖子,我使用promise在发回后做了一些事情

我的问题是如何将this.value (keyup value)传递给promise对象,因此{ search: inputData }可以有值发布

2 个答案:

答案 0 :(得分:5)

制作getData()和实际功能,因此可以使用参数。

jQuery的post()已经返回一个承诺,所以你不需要再次回合。

function getData( inputData ) {
  return $.post( "data.php", { search: inputData } );
}

this.inputText.on('keyup', function(){

    var inputData = this.value; 

    getData( inputData )
      .then(function(fromResolve){

        console.log(fromResolve);

       }).catch(function(fromReject){

        console.log(fromReject);

       });
});

答案 1 :(得分:0)

只需从jQuery回调函数调用resolve

var getData = new Promise(function(resolve, reject){
    $.post( "data.php", { search: inputData }, function( data ) { //need to pass this
        data = $.parseJSON(data);
        if (data) { resolve(data); }
        else { reject(); }
    });
});