Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  65] [ 4]  / answers: 1 / hits: 8919  / 10 Years ago, sat, may 24, 2014, 12:00:00

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/


More From » promise

 Answers
12

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'.


[#45072] Friday, May 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;