如何用新数组更新Promise.all?

时间:2017-08-15 19:24:18

标签: javascript node.js asynchronous promise es6-promise

在下面的代码中,我想执行abc,然后 a1 ,因为a1已添加到a中{1}}。但是,使用添加的新Promise.all更新a1似乎并非如此。最好的方法是什么?是否Promise全部更新?我尽量不在await a1内进行a

var arr = [];

async function a() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve a");
    arr.push(a1);
    resolve(1);
    }, 2000);
  });
}

async function b() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve b");
    resolve(2);
    }, 4000);
  });
}

async function c() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve c " + arr.length);
    resolve(3);
    }, 6000);
  });
}

async function a1() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve a1");
    resolve(11);
    }, 2000);
  });
}

arr = [a(), b(), c()];

(async function run() {
  await Promise.all(arr);
})();


console.log('Done');

2 个答案:

答案 0 :(得分:0)

有趣的问题......

您可能确实通过将承诺替换为另一个承诺来修改运行中的Promise.all(),即使新插入的承诺解析了最新承诺。

在下面的示例中,promise three将替换为一个新的promise,它将在2000ms后再解析,Promise.all()将等到它解析为包含它的解析值到提供给的数组.then()阶段。

var fun   = _ => new Promise((v,x) => setTimeout(v,2000,5)),
    one   = new Promise((v,x) => setTimeout(v,1000,1)),
    two   = new Promise((v,x) => setTimeout(v,2000,2)),
    three = new Promise((v,x) => setTimeout(v,3000,fun())),
    four  = new Promise((v,x) => setTimeout(v,4000,4));
Promise.all([one,two,three,four])
       .then(a => console.log(a));  

请等待5秒才能看到结果。

答案 1 :(得分:0)

首先,您将a1推到我认为您想要推送a1()的位置 - 否则您将推送功能,而不是承诺

但这不会改变任何东西,因为传递给Promise.all的数组(在我已经看到的每个库中)被复制(使用Array#slice)所以对传入的数组进行任何更改不可能"可见"到Promise.all(内部)代码

但是,你可以创建一个递归调用数组上的Promise.all的函数,直到结果的长度等于数组的(当前,新的)长度



var recursiveAll = a => Promise.all(a).then(r => r.length == a.length ? r : recursiveAll(a));

var arr = [];

async function a() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve a");
    arr.push(a1());
    resolve(1);
    }, 200);
  });
}

async function b() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve b");
    resolve(2);
    }, 400);
  });
}

async function c() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve c " + arr.length);
    resolve(3);
    }, 600);
  });
}

async function a1() {
  return new Promise(resolve => {
    setTimeout(() => {
    console.log("Resolve a1");
    resolve(11);
    }, 200);
  });
}

arr = [a(), b(), c()];

(async function run() {
  let results = await recursiveAll(arr);
  console.log(results);
})();