问承诺..when 和 .then 的区别 [英] Q promise. Difference between .when and .then

查看:69
本文介绍了问承诺..when 和 .then 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我虽然这段代码可以工作:

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

我的想法是:当 setTimeout 在四秒后完成它的工作时,Q 库将在第一个回调中捕获返回并显示具有两个属性的对象:newVal : 4message : 'it只是成为一个'+ 400.相反,我在成功回调中有奇怪的 1 个数字作为 obj...

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

顺便说一句,Q 库中的 .when.then 有什么区别?

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

推荐答案

.when() 接受一个或多个 promise 作为参数.您正在向它传递一个计时器句柄,因此它会立即执行 .then() 处理程序.

.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() 没有神奇的能力来辨别你传递给它的东西何时完成.您必须向它传递一个或多个承诺,并监控这些承诺何时得到解决.

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

此外,您不能从 setTimeout() 返回任何内容,但是如果您在 setTimeout() 中解析了一个承诺,您可以将数据传递给 .resolve() 方法.

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.

你可以这样做:

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

<小时>

但是,当您只有一个承诺时,您甚至不需要 Q.when().你可以这样做:

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

这篇关于问承诺..when 和 .then 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆