在此代码中,无论我将函数按什么顺序放置,目录中的文件始终会打印在目录名称之前:
var fs = require('fs');
fs.realpath(__dirname, function(err, path) {
if (err) {
console.log(err);
return;
}
console.log('Path is : ' + path);
});
fs.readdir(__dirname, function(err, files) {
if (err) return;
files.forEach(function(f) {
console.log('File: ' + f);
});
});
File: text_1.txt
File: text_2.txt
File: text_3.txt
Path: /home/user/docs
因此,如果 fs.readdir() 是第一个函数,则输出将是相同的。为什么会出现这种情况?
最佳答案
这些函数是asynchronous ,因此将它们放入文件中的顺序与执行操作的顺序关系不大。 readdir
操作可能要快得多,因此它在 realpath
操作之前完成。
为了按顺序执行这些操作,您可以将对其中一个操作的调用放在另一个操作的回调中。
var fs = require('fs');
fs.realpath(__dirname, function(err, path) {
if (err) {
console.log(err);
return;
}
console.log('Path is : ' + path);
fs.readdir(__dirname, function(err, files) {
if (err) return;
files.forEach(function(f) {
console.log('File: ' + f);
});
});
});
关于javascript - 为什么这个nodejs代码无论哪个函数在先都会以相同的顺序输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46396308/