蓝鸟承诺多层次

Bluebird promise multi-level

我正在努力弄清楚如何异步执行多个级别的承诺。我已经搜索过文档,但大多数承诺库让你等待所有承诺做一些逻辑或一个然后下一个。我需要这两者的一个方面。我写了一个快速演示,说明我要实现的目标。

这背后的总体思路是我有 4 个函数需要调用。 A & B 可以立即同时调用。 C依赖于B的return。然后我需要所有三个 (A、B、C) 来计算 D。我将如何构造它?

这里我试着画了大概的流程图:

A ->   -> D
B -> C ->

示例代码:

var bluebird = require('bluebird');

function a(){
  setTimeout(function(){
    console.log('a called');
    return 'a';
  },1000);
}

function b(){
  setTimeout(function(){
    console.log('b called');
    return 'b message';
  },1000);
}

function c(bMessage){
  setTimeout(function(){
    console.log('c called');
    return 'c set in motion';
  },1000);
}

function d(aMessage, bMessage, cMessage){
  setTimeout(function(){
    console.log('prmoises: called: ' + aMessage + bMessage + cMessage);
    return 'this the end';
  },1000);
}

function test(){
    // what goes here?
}

test();

returning promises from your asynchronous functions instead of just calling setTimeout. Best just drop the setTimeout completely and use <a href="http://bluebirdjs.com/docs/api/promise.delay.html" rel="nofollow noreferrer">Promise.delay(…)</a> 开始,然后 (…).

然后对单个依赖项使用 then,对多个依赖项使用 Promise.join。不要构建长链,将您需要的每个结果的承诺存储在变量中:

function test(){
    var aPromise = a();
    var bPromise = b();
    var cPromise = bPromise.then(c);
    return Promise.join(aPromise, bPromise, cPromise, d);
}

另见相关问题