我有一个循环。我正在循环内执行以下任务。
- 读取文件
- 将文件内容发送到网络服务并获取响应。
由于网络服务速度缓慢,我需要在这两个任务之间添加延迟。我在这两个任务之间使用了 setTimeout。问题是每个任务的执行顺序。当我记录每个任务的输出时,我可以看到它首先打印从文件读取的所有文件内容,然后打印“延迟”消息(n 次),然后打印来自服务调用的响应。根据控制台输出
[File 1 content]
[File 2 content]
[File 3 content]
Delayed
Delayed
Delayed
[Service response for File1]
[Service response for File2]
[Service response for File3]
看起来这三个任务是并行执行的,但不是顺序执行的。我的目标是按顺序执行它们。
我的代码中有什么问题导致了上述行为
以下是我的代码
function myFunction() {
console.log("Delayed");
}
filenames.forEach(function (filename) {
fs.readFile(dir + filename, 'utf8', function(err, fileContent) {
console.log(fileContent);
setTimeout(myFunction, 3000);
anotherAsyncServiceCall(fileContent, function (err, response) {
.....
)};
}
最佳答案
您可以通过不同的方式来实现您想要做的事情。
Using Promise as return
fs.readfile(dir + filename, 'utf8',function(err, fileContent){
if(err) throw err;
return anotherAsyncServiceCall(fileContent);
}).then(function(err, response){
if(err) throw err;
//return the response or do any thing
}).catch(function(exception){
console.log('exception occured',exception);
});
List all the promise and then execute them all at once using Promise.all()
//creating a global variable to contain our promises
var promiseList =[];
filenames.forEach(function (filename) {
var fileContent= fs.readFileSync(dir + filename, 'utf8');
promiseList.push(anotherAsyncServiceCall(fileContent));
});
然后使用Promise.all()
执行所有promise:
Promise.all(promiseList).then(function(err,response) {
console.log(response);
});
using async - await
fs.readfile(dir + filename, 'utf8',async function(err, fileContent){
if(err) throw err;
var response = await anotherAsyncServiceCall(fileContent);
return response;
}).catch(function(exception){
console.log('exception occured',exception);
});
Update the fs.readFile is not a promise but is async so it supports the callback.
关于javascript - 在两个任务之间添加延迟并获得意外的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839360/