【问题标题】:Equivalent of async.map in new ES6?等效于新 ES6 中的 async.map?
【发布时间】:2018-08-29 19:25:48
【问题描述】:

有没有办法使用新的“async”javascript 关键字来替换 async 模块中的 async.map?基本上我想尽可能避免使用异步模块。例如,一次读取多个文件,然后在读取完所有文件后执行操作。

【问题讨论】:

标签: javascript node.js asynchronous ecmascript-6 promise


【解决方案1】:

辅助函数:

async function asyncMap(array, callback) {
  let results = [];
  for (let index = 0; index < array.length; index++) {
    const result = await callback(array[index], index, array);
    results.push(result);
  }
  return results;
}

示例用法:

const titles = await asyncMap([1, 2, 3], async number => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${number}`
  );
  const json = await response.json();
  return json.title;
});

灵感来自async forEach

【讨论】:

  • asyncawait 是 ES8 规范,而不是 ES6。这也没有并行性,不像async.map()
【解决方案2】:

是的,通常您可以使用Promise.all 来执行此操作。

let urls = [...];

let promises = urls.map(function(url) {
    return fetch(url).then(result => result.json()); // or whatever
});

Promise.all(promises).then(function(results) {
    // deal with the results as you wish
});

或者,单行:

Promise.all(urls.map(url => fetch(url).then(res => res.json()))).then(function(results) {
    // deal with the results as you wish
});

虽然这不容易阅读,但我担心......

它不像async.map 那样流畅,当然编写一个合适的包装器并不难。

【讨论】:

  • 我认为它的回调传递比async.map 更容易阅读。您也可以使用async function(url) { return (await fetch(url)).json(); }(或类似的东西)进行回调
  • 如果你想使用 async 关键字你也可以:const results = await Promise.all(urls.map(url =&gt; ...))
  • 嗯,问题确实是 ES6,但是是的,它们都改进了一些东西。
  • 或者,为了绝对简洁(和混淆):let results = await Promise.all(urls.map(async url =&gt; (await fetch(url)).json()));
猜你喜欢
  • 2018-04-05
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2016-10-12
相关资源
最近更新 更多