Benjamin W
Benjamin W

Reputation: 2848

Javascript promise pass param into object

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);

    });
});

I have a jQuery ajax post and I use promise to do something after it post back

my problem is how can I pass this.value (keyup value) into promise object, so { search: inputData } can have value to post

Upvotes: 0

Views: 92

Answers (2)

Daniel A. White
Daniel A. White

Reputation: 190945

Simply call resolve from the jQuery callback function.

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(); }
    });
});

Upvotes: 0

Sirko
Sirko

Reputation: 74046

Make getData() and actual function, so it can take parameters.

jQuery's post() already returns a promise, so you don't need to wrap again.

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);

       });
});

Upvotes: 5

Related Questions