JavaScript异步/等待Array.map()中的Promises [英] JavaScript async/await for Promises inside Array.map()

查看:80
本文介绍了JavaScript异步/等待Array.map()中的Promises的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码

class SomeClass {
  async someFunc() {
    const urlParameters = [0, 1, 2];
    const batchAjaxResult = await urlParameters.map((parameter) => { 
        const result = await $.get(`someUrl/${parameter}`);
        return {
          parameter,
          result
        }
     });

  console.log(batchAjaxResult);

  }
}

JavaScript将返回一个已解析的数组Promise而不是实际的Promises结果。

JavaScript will return an Array of resolved Promises instead of the actual Promises result.

这可能是由于 Array.map()未实现为承诺。

This is probably due to Array.map() not being implemented as a Promise.

是否存在基于承诺的版本Array.map

这个问题不同于如何从异步调用中返回响应,因为它是关于如何返回包含在 Array.map 中的批量响应。

This is question differs from How to return the response from an asynchronous call, because it's about How to return batched responses wrapped inside Array.map.

推荐答案

你可以使用这个简单的函数链接promises来实现顺序执行:

You could use this simple function which chains the promises to achieve sequential execution:

function asyncMap(arr, mapper) {
  var q = Promise.resolve();
  return Promise.all(arr.map(v => q = q.then(() => mapper(v))));
}


// Usage

asyncMap([1, 2, 3], v => {
  return new Promise(resolve => {
    console.log("Start " + v);
    setTimeout(() => {
      console.log("End " + v);
      resolve("foo" + v);
    }, 500);
  });
}).then(a => console.log(a));

这篇关于JavaScript异步/等待Array.map()中的Promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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