【问题标题】:Execute async request inside .map loop in correct order以正确的顺序在 .map 循环中执行异步请求
【发布时间】:2021-02-01 06:26:54
【问题描述】:

我正在为内部的 .map 循环和异步函数而苦苦挣扎。我将 request-promise 用于异步请求。

  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

无法弄清楚我做错了什么。请帮忙。

【问题讨论】:

  • Promise.all 将按顺序为您提供结果,但您既不会在地图中返回任何内容,也不会使用来自Promise.all 的结果。就像 jfriend 所说的串行执行for of 会很好。

标签: javascript promise async-await request-promise array.prototype.map


【解决方案1】:

.map() 不知道async。它不会在您传递给它的回调函数中为 await 暂停其循环。相反,await 将立即导致async 函数返回一个未解决的承诺,.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 推荐用于所有新项目。我最喜欢的是 got(),它是从头开始使用 Promise 构建的,但您可以选择具有您想要的功能和/或您喜欢的 API 的任何一个。

【讨论】:

  • 谢谢!有用!但是有没有“for...of”循环的替代品?因为我的 eslint 抛出 no-restricted-syntax 错误
  • @tjnk24 - 为什么 eslint 抱怨 for/of 循环?也许想修复你的 eslint 设置。那是现代 JS 语法。如果你想要for (let i = 0; i < testArray.length; i++) { ... },你可以使用老式的for循环,然后在循环中引用testArray[i],但for/of是一种更新更好的编程方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多