首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Promise.all不等待完成内部Promise.all完成

Promise.all不等待完成内部Promise.all完成
EN

Stack Overflow用户
提问于 2020-09-17 12:41:16
回答 1查看 44关注 0票数 0
代码语言:javascript
复制
let obj = [
  {
    Id: 1,
    name: 'david',
    Address:[{
      city: 'dubai',
      country: 'UAE'
    }]
  },
  {
    Id: 2,
    name: 'Ram',
    Address: [{
      city: 'US',
      country: 'India'
    },
    {
      city: 'Delhi1',
      country: 'India1'
    }]
  }
];

async function fun() {
await Promise.all(obj.map(async info => {
      console.log('info', JSON.stringify(info));
      await Promise.all(info.Address.map(async (items, index) => {
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }));
      console.log('UpdatedInfo', JSON.stringify(obj));
    }));
}
 async function firstFunction() {
  return new Promise((resolve, reject) => {
    let y = 0;
    setTimeout(() => {
      for (let i = 0; i < 10; i++) {
        y++;
      }
      console.log('loop completed');
      resolve(y);
    }, 2000);
  });
 }

fun();

我得到的输出如下,它说

  1. info
  2. info
  3. loop completed
  4. promise解决了
  5. next step
  6. UpdatedInfo
  7. Loop completed
  8. next step
  9. UpdatedInfo

它应该能提供这样的输出,

  1. info
  2. loop completed
  3. Promise解决方案: 10
  4. next step
  5. UpdatedInfo
  6. info
  7. loop completed
  8. promise resolved: 10
  9. next step
  10. UpdatedInfo
EN

回答 1

Stack Overflow用户

发布于 2020-09-18 12:14:01

当您使用.map(async (e) => {...})时,所有函数都会同时开始执行。await Promise.all(arr.map(async (e) => {...}))等待它们全部完成,但它仍然是并行的。

你想要的是按顺序排列。可以使用for循环:

代码语言:javascript
复制
for (let info of obj) {
      console.log('info', JSON.stringify(info));
      for (let index = 0 ; index < info.Address.length; index++) {
      let items = info.Address[index];
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }
      console.log('UpdatedInfo', JSON.stringify(obj));
}

或者使用异步缩减:

代码语言:javascript
复制
await obj.reduce(async (memo, info) => {
      await memo;
      console.log('info', JSON.stringify(info));
      await info.Address.reduce(async (memo2, items, index) => {
        await memo2;
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }), Promise.resolve());
      console.log('UpdatedInfo', JSON.stringify(obj));
    }, Promise.resolve());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63938251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档