问题描述
我正在尝试使用异步/等待代码来读取文件.这是我的代码:
I am experimenting with async/await code to read file.Here's my code:
var fs = require('fs');
function readFile(fileName) {
return new Promise(resolve => {
//console.log(test);
fs.readFile(fileName, 'utf8', function (err, data) {
if (err) throw err;
console.log(fileName)
console.log(data)
})
resolve();
});
}
async function run() {
await readFile('file1.txt');
await readFile('file2.txt');
readFile('file3.txt');
}
run();
但是结果仍然是随机的.这意味着file3有时会在file2之前读取.我在哪里做错了?
But the result is still random. It means file3 sometime read before file2. Where am I doing wrong?
推荐答案
有很多方法可以实现.
我会写一个简单的:
1)使用util.promisify
将回调方法转换为promise:
1) using util.promisify
to convert callback method to promise:
const fs = require('fs');
const util = require('util');
const readFile = (fileName) => util.promisify(fs.readFile)(fileName, 'utf8');
(async () => {
try {
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
for (const file of files) {
console.log(
await readFile(file)
);
}
}
catch (error) {
console.error(error);
}
})();
2)*Sync
方法.由于您的代码未处理并发,因此可以使用*Sync
方法:
2) *Sync
methods. Since Your code is not dealing with concurrency You can use *Sync
methods:
const fs = require('fs');
try {
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
for (const file of files) {
console.log(
fs.readFileSync(file, 'utf8')
);
}
}
catch (error) {
console.error(error);
}
顺便说一句.这是您的固定代码:
BTW. Here is Your fixed code:
var fs = require('fs');
function readFile(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', function (error, data) {
if (error) return reject(error);
console.log(fileName)
console.log(data)
resolve();
})
});
}
async function run() {
await readFile('file1.txt');
await readFile('file2.txt');
await readFile('file3.txt');
}
run();
因为您正在调用readFile并以相同的异步序列解析它在同一时间被调用,这是race condition
的原因.
since You're calling readFile and resolve at same async sequence it's being called at same time which is reason of race condition
.
您必须等待回调处理,然后再解决它(在回调作用域内).
You've to wait for callback handling and then resolve it (inside callback scope).
这篇关于Node.js使用async/await读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!