承诺数组中的承诺数组

我有一个包含书籍数据的数组。我必须在数组中循环并进行服务调用以获取每本书的详细信息,并且每本书数据具有与该书相关联的附件的ID,并进行服务调用以获取每本书的相关附件。

这里的问题是promise.all不等待attachmentpromises得到解决

  function ExportbooksData(books) {
  return new Promise((resolve, reject) => {
    if (books && books.length > 0) {
      let aPromises = [];
      for (let i = 0; i < books.length; i++) {
        const id = books[i].id;
        const name = books[i].name;
        aPromises.push(this.getBooksData(name, id, null).then(results => {
          let aAttachmentPromises = [];
          Object.entries(results).forEach(([key, value]) => {
            let fieldName = key;
            if (value.constructor === Array && value.length > 0) {
              aAttachmentPromises.push(this.getAttachments(fieldName).then(fileContent => {
              }))
            }
          });
        }));
      }
      // Resolve when all are done!
      Promise.all(aPromises)
        .then(results => resolve(results))
        .catch(error => reject(error));
    }
  })
}
评论
  • 为你痴迷
    为你痴迷 回复

    You build up aAttachmentPromises but you don't return it, so your aPromises.push always pushes a Promise that resolves immediately with undefined into the array that you're waiting on. Change your code like this:

    aPromises.push(
      this.getBooksData(name, id, null).then(results => {
        let aAttachmentPromises = [];
        Object.entries(results).forEach(([key, value]) => {
          let fieldName = key;
          if (value.constructor === Array && value.length > 0) {
            aAttachmentPromises.push(this.getAttachments(fieldName).then(fileContent => {}));
          }
        });
        return aAttachmentPromises; // <--- here!
      })
    );