我已经阅读了一些有关异步/等待的文档,并尝试附带一个示例来更好地理解它。我所期望的是,下面没有异步和等待的代码将首先打印字符串“ Completed”,然后打印文件内容。但是即使添加了异步并等待之后,我仍然看到打印顺序不受影响。我的印象是异步的,在这种情况下等待使用将首先打印文件内容,然后打印字符串“ Completed”。
var fs = require('fs');
getTcUserIdFromEmail();
async function getTcUserIdFromEmail( tcUserEmail ) {
let userInfo = {};
let userFound = false;
// Read the file that is containing the information about the active users in Teamcenter.
await fs.readFile('tc_user_list.txt', function(err, data) {
if( err )
console.log( err );
else
console.log( data.toString() );
});
console.log( 'Completed method');
}
请您指出我做错了。
谢谢, 帕万。
答案 0 :(得分:2)
await
仅在等待表达式返回 Promise 时有效。 fs.readFile
不会返回承诺,因此您的await
现在什么也没做。
幸运的是,节点提供了fs.promises.readFile
类似于fs.readFile
的功能,但是它没有期望回调,而是返回了promise。
const fs = require('fs')
现在您可以await fs.promises.readFile(...)
getTcUserIdFromEmail(); // > contents_of_tc_user_list
// Completed method
async function getTcUserIdFromEmail( tcUserEmail ) {
let userInfo = {};
let userFound = false;
const data = await fs.promises.readFile('tc_user_list.txt')
console.log(data.toString())
console.log( 'Completed method');
}