【问题标题】:How to wait for promise in synchronous nodejs function?如何在同步nodejs函数中等待promise?
【发布时间】:2018-01-15 12:11:47
【问题描述】:

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

  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.logthis.initUsers(); 完成之前执行。我怎样才能让它等待呢?

【问题讨论】:

  • 返回承诺和this.initUsers().then...?
  • 你不能“同步等待一个承诺”。返回一个promise,调用者在promise上使用.then()来知道它什么时候完成。
  • 也许我问错了问题。与其等待承诺,我可以摆脱承诺stackoverflow.com/questions/45571213/…

标签: node.js asynchronous callback promise async-await


【解决方案1】:

你必须这样做

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 2020-03-24
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2020-09-23
    • 2020-06-03
    • 2017-01-15
    相关资源
    最近更新 更多