javascript - async/await 不会将构建的数组返回到父 array.map()

标签 javascript node.js ecmascript-6 promise async-await

在以下代码中,expiringContentsAllBU 填充在 array.map() 内部的异步/等待函数 getOnlyContentWhatsNewReport 中,但在 businessUnits.map() 函数外部访问时 expiringContentsAllBU 会变为空。

const getExpiringContents = async () => {
  let businessUnits = Object.keys(contentFulSpaces);  
  let expiringContentsAllBU = [];
  businessUnits.map( async (bu) => {
      await getOnlyContentWhatsNewReport(bu, (err, result) => { 
        if(result) {
          let expiringContentsByBU = {};
          expiringContentsByBU['businessUnit'] = bu;
          expiringContentsByBU['expiringContents'] = result;
          expiringContentsAllBU.push(JSON.parse(JSON.stringify(expiringContentsByBU)));
        } else console.log('No expiring contents found for WhatsNewSection');
      })
    });
    console.log('result', expiringContentsAllBU);
}

最佳答案

var getOnlyContentWhatsNewReport = Promise.resolve(123);

const getExpiringContents = async () => {
  let businessUnits = [{ id: 1 }, { id: 2 }, { id: 3 }];  
  const expiringContentsAllBU = await Promise.all(businessUnits.map(async (bu) => {
      return getOnlyContentWhatsNewReport.then(respBu => {
        bu.businessUnit = respBu;
        return bu;
      }).catch((err) => {
        console.log('No expiring contents found for WhatsNewSection');
        return null;
      });
   }));
   console.log('result', expiringContentsAllBU);
}

getExpiringContents();

您必须等到映射完成且所有回调完成。 console.log 和后续代码块将在 map 完成之前执行,因此

const getExpiringContents = async () => {
  let businessUnits = Object.keys(contentFulSpaces);  
  const expiringContentsAllBU = await Promise.all(businessUnits.map(async (bu) => {
      return getOnlyContentWhatsNewReport(bu, (err, result) => { 
        if(result) {
          let expiringContentsByBU = {};
          expiringContentsByBU['businessUnit'] = bu;
          expiringContentsByBU['expiringContents'] = result;
          return JSON.parse(JSON.stringify(expiringContentsByBU);
        } else {
          console.log('No expiring contents found for WhatsNewSection');
          return null;
        }
      })
   }));
   console.log('result', expiringContentsAllBU);
}

关于javascript - async/await 不会将构建的数组返回到父 array.map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834513/

相关文章:

javascript - 根据 ul ID 将相同的类添加到子元素

javascript - 谷歌地图 : Zoom and pan inside a sub bounding box in the main viewport

javascript - javascript 中 if 语句被跳过

node.js - 如何在 Digital Ocean 上为 Unity 设置 Socket.io 服务器?

c# - 使用 Node JS - REST API 在 Office365 上召开 session 室 session

javascript - 清除搜索字段后,如何将 <div> 重置回 AJAX 响应之前的状态?

javascript - 用于绘制 MGRS 的叠加层

javascript - For Loop Works 但 return 没有意义

javascript - 如何在不通过引用传递该对象的情况下将对象插入数组?

javascript - 通过将嵌套属性提升到一个级别来转换 javascript 对象