正如async所说,pormise对象或简单数据(例如数字或字符串)可以跟随await,当它是简单数据时,它就像同步一样,我编写以下第一个程序:
let fs = require('fs');
async function readF(){
let data1 = await fs.readFileSync('./file1.txt','utf-8');
console.log(data1);
let data2 = fs.readFileSync('./file2.txt','utf-8');
console.log(data2);
}
readF();
console.log('outter hello');
结果是:
outter hello
first file
second file
看来readF函数是异步的?为什么?
我编写了第二个程序,只需将 await 更改为第二个文件阅读器:
let fs = require('fs');
async function readF(){
let data1 = fs.readFileSync('./file1.txt','utf-8');
console.log(data1);
let data2 = await fs.readFileSync('./file2.txt','utf-8');
console.log(data2);
}
readF();
console.log('outter hello');
这一次,结果是:
first file
outter hello
second file
我无法理解这个奇怪的惊人结果,希望你能帮助我。