首页 > 解决方案 > 我将如何做一个等待直到我的函数完成每个循环的 for 循环?

问题描述

我目前的代码是这样的:

const fs = require('fs');
var file = fs.readFileSync('file.txt').toString().split("\n");

for(i in file) {
    var [thing1, thing2, thing3] = file[i].split(":");
    myfunction(thing1, thing2, thing3);
}

这会为文件中的每一行执行一个函数,其中包含文件中的一些信息。由于技术原因,我一次只能让该功能运行一次。如何让 for 循环在再次循环之前等待函数完成?

标签: javascriptnode.jsfor-loop

解决方案


如果 myfunction 是同步一,则您的代码已经在工作

否则:

await myfunction(thing1, thing2, thing3);

确保将async添加到代码块中:

(async () => {
  for(i in file) {
     var [thing1, thing2, thing3] = file[i].split(":");
     await myfunction(thing1, thing2, thing3);
}})();

推荐阅读