如何在同步nodejs函数中等待promise?

Din*_*ent 5 asynchronous callback node.js promise async-await

我使用异步方法创建了一个包含我的用户凭据的解密文件:

  initUsers(){

    // decrypt users file
    var fs = require('fs');
    var unzipper = require('unzipper');

    unzipper.Open.file('encrypted.zip')
            .then((d) => {
                return new Promise((resolve,reject) => {
                    d.files[0].stream('secret_password')
                        .pipe(fs.createWriteStream('testusers.json'))
                        .on('finish',() => { 
                            resolve('testusers.json'); 
                        });
                });
            })
            .then(() => {
                 this.users = require('./testusers');

            });

  },
Run Code Online (Sandbox Code Playgroud)

我从同步方法调用该函数。然后我需要在同步方法继续之前等待它完成。

doSomething(){
    if(!this.users){
        this.initUsers();
    }
    console.log('the users password is: ' + this.users.sample.pword);
}
Run Code Online (Sandbox Code Playgroud)

console.log之前执行this.initUsers();完成。我怎样才能让它等待?

mar*_*308 0

你必须做

doSomething(){
    if(!this.users){
        this.initUsers().then(function(){
            console.log('the users password is: ' + this.users.sample.pword);
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

你不能同步等待异步函数,你也可以尝试 async/await

async function doSomething(){
    if(!this.users){
        await this.initUsers()
        console.log('the users password is: ' + this.users.sample.pword);
    }

}
Run Code Online (Sandbox Code Playgroud)