简体   繁体   English

将承诺链接到 Promise.all 不适用于嵌套地图?

[英]Chaining promises to a Promise.all doesn't work with nested maps?

Originally I had some code that looked like this...最初我有一些看起来像这样的代码......

function attachFilesToSelectedItems(file, item, server) {
  try {
    return await Promise.all(
      files.map(file => {
        return items.map(item=> {
          const formData = new FormData();
          formData.append("attachment", file);
          return server.addAttachment(item, formData);
        });
      })
    );
  } catch {
    return _strings.uploadError;
  }
}

But this doesn't seem to work as expected, it doesn't wait for all the server.addAttachment calls to finish.但这似乎没有按预期工作,它不会等待所有server.addAttachment调用完成。

Changing it around to not use maps and make a new Promise does fix it.将其更改为不使用地图并制作新的 Promise 确实可以修复它。

function attachFilesToSelectedItems(file, item, server) {
  const promises = [];
  files.forEach(file => {
    items.forEach(item => {
      const formData = new FormData();
      formData.append("attachment", file);
      promises.push(server.addAttachment(item, formData));
    });
  });
  return Promise.all(promises).catch(() => {
    return _strings.uploadError;
  });
}

Why does the approach to chain map values and using async/await not work?为什么链接 map 值和使用异步/等待的方法不起作用?

Why would it wait for a nested array in the first place?为什么它首先要等待嵌套数组?

Wrap nested array in Promise.all to create a promise out of it将嵌套数组包装在Promise.all中以从中创建 promise

function attachFilesToSelectedItems(file, item, server) {
  try {
    return await Promise.all(
      files.map(file => {
        return Promise.all(items.map(item=> {
          const formData = new FormData();
          formData.append("attachment", file);
          return server.addAttachment(item, formData);
        }));
      })
    );
  } catch {
    return _strings.uploadError;
  }
}

the result of the first level map doesn't return what you think it does, so in the end it's trying to run Promise.all on an array of arrays of promises, you would have to flatten it:第一级 map 的结果没有返回您认为的结果,因此最终它尝试在 arrays 的数组上运行 Promise.all

files.map(file => {
  return items.map(item=> {
    const formData = new FormData();
    formData.append("attachment", file);
      return server.addAttachment(item, formData);
    });
  })

returns [[promise, promise, ...], [promise, promise, ...]]返回[[promise, promise, ...], [promise, promise, ...]]

and Promise.all doesn't know how to handle it和 Promise.all 不知道如何处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM