在新ES6中等同于async.map?

时间:2018-03-20 20:17:23

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

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

2 个答案:

答案 0 :(得分:3)

是的,通常您可以使用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那么光滑,但当然写一个合适的包装并不难。

答案 1 :(得分:0)

辅助功能:

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;
});

样品用量:

{{1}}

受此async forEach

的启发
相关问题