首页 > 解决方案 > 异步等待正确使用

问题描述

我已经阅读了一些关于 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');
}

请您指出我做错了什么。

谢谢,帕万。

标签: node.jsasync-await

解决方案


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');
}

推荐阅读