javascript - 我将如何做一个等待直到我的函数完成每个循环的 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 循环在再次循环之前等待函数完成?
解决方案
如果 myfunction 是同步一,则您的代码已经在工作
否则:
await myfunction(thing1, thing2, thing3);
确保将async添加到代码块中:
(async () => {
for(i in file) {
var [thing1, thing2, thing3] = file[i].split(":");
await myfunction(thing1, thing2, thing3);
}})();
推荐阅读
- css - 如何防止css-grid中的白细胞
- php - PhpSpreadsheet - 从分隔文件导入日期
- unity3d - Firebase Unity 远程配置:MinimumFetchInternalInMilliseconds 无法按预期工作
- ffmpeg - FFMPEG:如何在创建多个流时混合不同类型的图像序列输入
- xamarin - Xamarin 窗体 UWP 应用程序在窗口调整大小后不会调整元素大小
- node.js - Axios 和 Oauth1.0 - '状态:400,错误请求'
- blazor - 通知 EditContext 该字段已更改以进行 Blazor 验证
- javascript - 如何防止传播运算符保持原始参考?
- java - 主线程上的 Android 处理程序使应用程序崩溃
- python - Django url re_path 无法重定向到正确的视图