Q诺..when和.then之间的区别

cac*_*ito 2 javascript promise q

我虽然这段代码会起作用:

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...');
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

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

BT 在Q库.when.thenQ库之间有什么区别?

jfr*_*d00 8

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

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

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

你可以这样做:

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...');
});
Run Code Online (Sandbox Code Playgroud)

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

promise(400).then(function(obj) {
    return console.log('jaaaaj !', obj);
}, function() {
    return console.log('rejected...');
});
Run Code Online (Sandbox Code Playgroud)