如何在形状像钻石的js中创建承诺链

时间:2017-09-14 01:01:27

标签: javascript node.js ecmascript-6 promise es6-promise

我坚持承诺。

说我的程序结构是这样的

            Func A             //gets data then passes to I1 and J2
         /          \
      Func I1      Func J1     //then route I & J run without interaction
        |            |
      Func I2      Func J2     
         \          /
             Func B            //Func B gets both the result of both

让这个工作变得有点麻烦。 我到目前为止

  getdata.then(data=>{
      var methods = Promise.all([
        funci1.x(data).then(output=>{
          funci2.x(output)
        }),
        funcj1.x(data).then(output2=>{
          funcj2.x(output2)
        })
      ])
      methods.then(([a,b])=>{
        console.log(a,b);
      })
  })

但它似乎没有起作用。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

您不能在两个Promise回调中返回任何可以投放到then()的内容,因此请将其更改为:

getdata.then(data => {
  var methods = Promise.all([
    funci1.x(data).then(output => funci2.x(output)),
    funcj1.x(data).then(output2 => funcj2.x(output2))
  ])
  methods.then(([a, b]) => {
    console.log(a, b);
  })
})

答案 1 :(得分:1)

我个人认为以这种方式编写的承诺更容易识别正在发生的事情。

const funcJ1 = (num) => {
  num = num + 1;
  return funcJ2(num);
}
const funcJ2 = (num) => (
  new Promise((resolve, reject) => {
    num = num + 1;
    resolve(num);
  })
);

const funcI1 = (num) => {
  num = num + 1;
  return funcI2(num);
}
const funcI2 = (num) => (
  new Promise((resolve, reject) => {
    num = num + 1;
    resolve(num);
  })
);

const funcB = (result) => {
  let total = 0;
  total = total + result[0]; // first promise result
  total = total + result[1]; // second promise result
  console.log(total); 
};

const funcA = (x) => {
    const promises = [];
    promises.push(funcJ1(x));
    promises.push(funcI2(x));
    Promise.all(promises).then((res) => {
      funcB(res); // done with I and J
    }).catch((e) => {
      throw e;
    });
}

funcA(1);

funcJ1和funcI1将并行运行,funcB将在funcJ2和funcI2完成后运行。

请参阅此jsfiddle https://jsfiddle.net/6fvLw8wv/