首页 > 解决方案 > NodeJS:如何在 For Loop 中等待 HTTP Get 请求完成?

问题描述

我在 NodeJS 中有一个 for 循环函数。我想等到 Http Get 请求的结果在 For Loop 中完成后再执行下一次迭代,我该如何实现呢?

for (let k=0; k<fd.length; k++) {
    url = fd[k].nct_id;

    HttpSearch({condition: url}).then(trials => {
         //Get the result first before execute the next iteration
         console.log(trials);
    });
}

标签: node.js

解决方案


你应该做for循环async

const main = async () => {
  for (let k = 0; k < fd.length; k++) {
    const url = fd[k].nct_id;

    const trials = await HttpSearch({ condition: url });

    console.log(trials);
  }
};

main().catch(console.error);

这将导致循环在每个HttpSearch.


推荐阅读