ES7 Getting result from an array of promises using await generator

早过忘川 提交于 2019-12-10 00:40:36

问题


Given an array of promises, what's the idiomatic way to get the results in ES7?

Here's what I want to do:

async function getImports() {
  let imports = [System.import('./package1.js'), System.import('./package2.js')];
  let promises = await* imports;
  let results = [];
  await promises.forEach(val => val.then(data => results.push(data))); //seems hacky
  console.log(results); // array of 2 resolved imports
}

The result is correct, but I'm still doing a forEach and a then to turn the resolved promises into results. This just doesn't seem right to me. Is there a cleaner way?


回答1:


As mentioned in the issue you filed, the core issue is that await* is no longer a thing and has been removed. Unfortunately, it was not properly throwing a syntax error in Babel 6 and was essentially being treated like a normal await.

You'll need to explicitly

 let [p1, p2] = await Promise.all([
          System.import('./package1.js'), System.import('./package2.js')]);



回答2:


I cannot believe it actually works, forEach does return undefined which you cannot await. If you need a loop, use map to get an array of (promised) results.

In your case, you seem to be looking for a simple

async function getImports() {
  let promises = [System.import('./package1.js'), System.import('./package2.js')];
  let results = await Promise.all(promises)
  console.log(results);
}



回答3:


One way to do it this ....

async function abc() {
    let p1 = getReviews();
    let p2 = getMenu();
    let [reviews, menu] = await results(p1, p2);
}

function results(...rest) {
    return Promise.all(rest).catch(err => console.log(err));
}


来源:https://stackoverflow.com/questions/34382710/es7-getting-result-from-an-array-of-promises-using-await-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!