以正确的顺序在 .map 循环中执行异步请求

Execute async request inside .map loop in correct order

我正在努力处理内部的 .map 循环和异步函数。我对异步请求使用请求承诺。

  import * as rp from 'request-promise';

  const testArray = ['one', 'two', 'three'];
  const link = 'https://somelink.com/';

  const test = testArray.map(async (elem) => {
    console.log('before', elem);

    await rp.get(link)
      .then(async () => {
        console.log('success');
      });

    console.log('after', elem);
  });

  Promise.all(test);

这段代码的输出:

before one
before two
before three
success
after one
success
after three
success
after two

我需要的是代码以正确的顺序执行,输出如下:

before one
success
after one
before two
success
after two
before three
success
after three

不知道我做错了什么。请帮忙。

.map() async 不知道。它不会在您传递给它的回调函数中为 await 暂停循环。相反,await 将立即导致 async 函数 return 一个未解决的承诺,而 .map() 将继续进行循环的其他迭代。您似乎已经知道 .map() 的结果数组将只是这些承诺的数组。

如果您希望循环暂停并等待 await,这样您就可以真正对异步操作进行排序,然后使用普通的 for 循环,而不是 .map() 循环.

 import * as rp from 'request-promise';

  const testArray = ['one', 'two', 'three'];
  const link = 'https://somelink.com/';

  for (let elem of testArray) {
    console.log('before', elem);

    await rp.get(link)
      .then(async () => {
        console.log('success', elem);
      });

    console.log('after', elem);
  });

这将依次执行您的 rp.get() 操作,等待第一个操作完成,然后再执行第二个操作。您的 .map() 循环正在并行执行它们,这意味着您无法控制执行顺序。


仅供参考,request() 库及其相应的衍生产品已被弃用,将不再积极开发以添加新功能。有一个备选方案列表 here that are recommended for all new projects. My favorite is got() 从头开始​​构建以使用 promises,但您可以选择具有您想要的功能的任何一个 and/or 和您喜欢的 API。