Q promise. Difference between .when and .then

2019-07-24 07:53发布

问题:

I though this code will work:

var promise = function(val) {

    var _val = val;

    return setTimeout(function(_val) {

        var newVal = val / 10;

        return {
            newVal : newVal,
            message : 'it just to be a ' + val
        };
    }, 3000);
};

Q.when(promise(400)).then(function(obj) {
    return console.log('jaaaaj !', obj);
}, function() {
    return console.log('no yet...');
});

JSFiddle

My thinking was like: when setTimeout finish its job after four seconds, Q library will catch return in first callback and show object with two properties: newVal : 4 and message : 'it just to be a ' + 400. Instead I have weird 1 number as obj in success callback...

BTW what is a difference between .when and .then in Q library?

回答1:

.when() takes one or more promises as arguments. You are passing it a timer handle so it will just execute the .then() handler immediately.

.when() has no magic ability to discern when something you pass to it is done. You must pass it one or more promises and it monitors when those promises are resolved.

Also, you can't return anything from a setTimeout(), but if you resolved a promise inside the setTimeout() you could pass data to the .resolve() method.

You could do something like this:

var promise = function(val) {
    var defer = Q.defer();

    setTimeout(function() {

        var newVal = val / 10;

        defer.resolve({
            newVal : newVal,
            message : 'it just to be a ' + val
        });
    }, 3000);

    // return the promise
    return defer.promise;
};

Q.when(promise(400)).then(function(obj) {
    return console.log('jaaaaj !', obj);
}, function() {
    return console.log('rejected...');
});

But, when you only have one promise, you don't even need Q.when(). You could just do this:

promise(400).then(function(obj) {
    return console.log('jaaaaj !', obj);
}, function() {
    return console.log('rejected...');
});