ES7使用await生成器从一组诺言中获取结果 [英] ES7 Getting result from an array of promises using await generator

查看:102
本文介绍了ES7使用await生成器从一组诺言中获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一系列承诺,在ES7中获得结果的惯用方式是什么?

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

这就是我想要做的:

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
}

结果是正确的,但我仍在执行forEachthen来将已解决的承诺转化为结果.这对我来说似乎不对.有没有更清洁的方法?

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?

推荐答案

如您所提问题中所述,核心问题是await*不再是问题,已被删除.不幸的是,它在Babel 6中没有正确引发语法错误,并且实际上被视为普通的await.

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.

您需要明确

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

这篇关于ES7使用await生成器从一组诺言中获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆