Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument to "then" function

I'm trying to learn using deferred and I'm stumbled as I'm not getting expected arguments in the "then" block.

var makeCall = function (err, param) {
  var deferred = Q.defer();
  setTimeout(function() {
    console.log(1111, err, param);
    deferred.resolve(err, param);
  }, 1000);
  return deferred.promise;
};

makeCall('test', '11').then(function(err, data) {
  console.log(222, err, data);
});

Console. with 1111 outputs correct data that was returned from an Ajax call but 222 does not.

http://jsfiddle.net/M2V44/

like image 818
Anatoli Avatar asked May 24 '14 14:05

Anatoli


1 Answers

deferred.resolve can accept only one argument and that is to mark the success of the asynchronous call. To notify of the failure, you need to use deferred.reject. So your code has to be changed like this

var makeCall = function(err,param){
    setTimeout(function () {
        console.log(1111, err, param);
        var deferred = Q.defer();
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(param);
        }
    }, 1000);
    return deferred.promise;
};

makeCall(undefined, '11').then(function (data) {
    console.log(222, data);
}, function (err) {
    console.log(333, err);
});

This will print 222 '11', to simulate the failure case, just invoke makeCall with any Truthy value as the first argument, for example

makeCall('11')....

it will invoke the failure handler, and the output will be 333 '11'.

like image 198
thefourtheye Avatar answered Sep 28 '22 14:09

thefourtheye