Q promise. Difference between .when and .then

拈花ヽ惹草 提交于 2019-12-24 03:18:06

问题


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...');
});


来源:https://stackoverflow.com/questions/25613624/q-promise-difference-between-when-and-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!