【问题标题】:is it possible at Promise.all add later a Promise to Array?是否可以在 Promise.all 稍后向数组添加一个 Promise?
【发布时间】:2020-02-20 20:05:33
【问题描述】:

我在做一个项目,我问自己在 Javascript 中启动 Promise.all 是可行的,他们确实向数组添加了进一步的 Promise 以及它们是否也在运行?

【问题讨论】:

  • 你的意思是在你的 Promise 数组中有一个 Promise 在你调用 Promise.all 之后附加另一个 Promise 吗?
  • 喜欢:var PromiseAr = [] function func1(){ new Promise((resolve,reject) => { PromiseAr.push(func1()) }); } func1(); Promise.all(PromiseAr).then(() => { console.log("done"); })

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


【解决方案1】:
  const runAsyncFunctions = async () => {
  const users = await getUsers()

  if(users){
    Promise.all(
      users.map(async user => {
        const userId = await getIdFromUser(user)
        console.log(userId)

        const capitalizedId = await capitalizeIds(userId)
        console.log(capitalizedId)
      })
    )
      console.log(users)
  }
}

【讨论】:

    【解决方案2】:
    var promise1 = Promise.resolve(3);
    var promise2 = 42;
    var promise3 = new Promise(function(resolve, reject) {
      setTimeout(resolve, 100, 'foo');
    });
    
    Promise.all([promise1, promise2, promise3]).then(function(values) {
      console.log(values);
    });
    promise.all() work like this...
    

    【讨论】:

    • 但是如果你有一个带有 Promise 的数组并在 Promise.all 工作时添加一个 Promise 怎么办
    猜你喜欢
    • 2017-07-01
    • 2019-06-24
    • 2021-01-23
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2019-03-08
    相关资源
    最近更新 更多