Q.all返回异步函数而不是我想要解析的值

时间:2014-07-18 05:10:10

标签: javascript node.js promise q

这是我的小型演示脚本。

我的想法是,在我的保证链中的某个时刻,我将调用doAll调用Q.all来处理一批异步操作。然后在我进入下一个promise链之前返回结果,因为我将调用的下一个方法实际上可能需要Q.all的结果。

我觉得下面的代码没有达到我的最终目标,但是现在,doAll只是解决了函数而不是我真正想要解决的值。 Q.all甚至没有等Q.delay做任何事情。

输出

vagrant@precise64:~$ node p.js
Starting step 1
the then after doAll
[ [Function: doAsync], [Function: doAsync] ]

代码

var Q = require('q');

function doAsync() {
    console.log('doing async');
    return Q.delay(3000).thenResolve('finished');
};

// A helper function that calls a batch of async operations
// In real code this could be a mix of async calls.
function doAll() {
    var deferred = Q.defer();
    Q.all([doAsync, doAsync])
     .then(function (results) {
        deferred.resolve(results);
      });
    return deferred.promise;
};

// In real app this function may have a chained
// of promises (step1 - 3)
//     step1()
//       .step2()
//       .step3()
//       .doAll()
//       .tearDown()
//       .done();
// But here we just imagine all these steps in
// a single function.
function starter() {
    console.log("Starting step 1");
    return Q.delay(1000);
}

// Idea:
// We start with 1 or more steps, then we
// call doAll and wait for all of them to complete
// before return the batch result.
starter()
  .then(function () {
    doAll()
    .then(function(results) {
        console.log("the then after doAll");
        console.log(results);
    })
});

上面使用Q.delay的代码受此演示代码的启发:http://jsfiddle.net/jfromaniello/FRRxM/3/light/

1 个答案:

答案 0 :(得分:4)

您在结果中获得了一系列函数,因为Q.all应该作为promises的参数数组接收,而不是创建该promise的工厂函数数组。您可以找到的文档here

此外,您不需要创建另一个延迟对象来从Q.all获取结果并将其传递给下一个异步函数:

<强>的JavaScript

function doAsync1() {
    console.log('Async 1');
    return Q.delay(3000).thenResolve('finished1');
};

function doAsync2() {
    console.log('Async 2');
    return Q.delay(3000).thenResolve('finished2');
};

function starter() {
    console.log("Starter");
    return Q.delay(1000);
}

function doAll() {
    return Q.all([doAsync2(), doAsync2()]);
}

starter().
    then(doAsync1).
    then(doAll).
    then(function(results) {
        console.log("after doAll");
        console.log(results);
    });

<强>结果

Starter
Async 1
Async 2
Async 2
after doAll
["finished2", "finished2"] 

示例: http://jsfiddle.net/St7YS/1/

相关问题