node.js - 异步等待正确使用
问题描述
我已经阅读了一些关于 async/await 的文档,并尝试通过一个示例来更好地理解它。我所期待的是,下面没有 async 和 await 的代码将首先打印字符串“Completed”,然后是文件的内容。但即使在添加了 async 和 await 之后,我也看到打印顺序没有受到影响。我的印象是异步的,在这种情况下等待使用将首先打印文件内容,然后是字符串“已完成”。
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');
}
请您指出我做错了什么。
谢谢,帕万。
解决方案
await
仅当正在等待的表达式返回Promise时才有效。fs.readFile
不返回承诺,所以现在你await
什么都不做。
对我们来说幸运的是,node 提供了一个fs.promises.readFile
类似fs.readFile
但不期望回调的函数,它返回一个承诺。
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');
}
推荐阅读
- php - 如何在 TYPO3 9LTS 中使用 SQLite 进行 PHPUnit 功能测试
- amp-html - 'on' 属性内的 amp-bind JS 操作
- arrays - 用 awk 打印数组的每个元素
- schema.org - 一组事物的 Schema.org 标记是什么?
- rdf - Protégé 中 rdfs:label 的更改顺序
- sd-card - 如何读取/写入字节到 MC60A 的 SD 卡插槽?
- javascript - 如何将数组映射到日期?
- css - 元素的条件样式
- postgresql - Go Lang, Postgres: cannot get oid after Scan
- python - PyMongo:无法列出数据库集合