簡體   English   中英

如何解決javascript中的異步等待問題?

[英]how to resolve the async await issue in javascript?

以下是我的代碼

 let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical.async.parseICS(text); const objectKeys = Object.values(data); const filterObj = objectKeys.length === 1 || objectKeys[0].type === 'VEVENT' ? objectKeys[0] : objectKeys[1]; const desiredObj = { subject: filterObj.summary.val ? filterObj.summary.val : filterObj.summary, description: filterObj.description.val ? filterObj.description.val : filterObj.description, dateStart: moment(filterObj.start).format('YYYY-MM-DDTHH:mm:ss\\\\Z'), dateEnd: moment(filterObj.end).format('YYYY-MM-DDTHH:mm:ss\\\\Z'), organizer: filterObj.organizer.params.EMAIL ? filterObj.organizer.params.EMAIL : filterObj.organizer.val.split('mailto:').join(''), invites: filterObj.attendee.length === undefined ? filterObj.attendee.params.EMAIL ? filterObj.attendee.params.EMAIL : filterObj.attendee.val.split('mailto:').join('') : filterObj.attendee.map( (invite) => invite.params.EMAIL ? invite.params.EMAIL : invite.val.split('mailto:').join('') ), location: filterObj.location.val ? filterObj.location.val : filterObj.location }; icsFileData.push(desiredObj); }); //const icsFileDataArray = await Promise.all(icsFileData); console.log('jhgjhgjhgj: ', await icsFileData);

請檢查是什么問題,我嘗試了很多次總是得到相同的結果。

這是此代碼始終返回我的結果

[ Promise { <pending> } ]

要明白的事情,

  1. async/await只是一種以同步方式編寫異步代碼的語法糖
  2. .map(async() => { ...})的回調將返回一個Promise
  3. 所以在你的代碼中, icsFileData是一個Promise的集合,所以你必須使用Promise.all來解析所有的 promise 才能得到想要的結果
let icsFileData = [];
icsFileData = filterAttachmentArray.map(async(file) => {
  ....
  // you dont need this line, you can simply return the desiredObj
  // icsFileData.push(desiredObj);
  return desiredObj;
});
// this does the magic, since, icsFileData is a array of Promise
const icsFileDataArray = await Promise.all(icsFileData);
console.log('result: ', icsFileDataArray);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM