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

问题描述 投票:0回答:1

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

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

            });

  },

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

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

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

node.js asynchronous callback promise async-await
1个回答
0
投票

你必须这样做

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

}

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

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

}
© www.soinside.com 2019 - 2024. All rights reserved.