node.js - 如何等待同步 nodejs 函数中的 promise ?

标签 node.js asynchronous callback 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');

            });

  },

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

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

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

最佳答案

你必须做

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

}

关于node.js - 如何等待同步 nodejs 函数中的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45559588/

相关文章:

JavaScript:一个一个地执行异步函数

node.js - 尝试为 Google 身份验证器插入 QR 码图像时出现 400 Bad Request

node.js - 运行 Node 命令作为 grunt 驱动的 QUnit 测试的一部分

javascript - Jade 条件语句呈现为纯文本

asynchronous - Oozie > 异步操作和同步操作有什么区别

javascript - 如何使用异步操作 WinJS 在 for 循环后执行操作

Swift 为嵌套回调保护弱 self

linux - Linux 中的异步套接字——轮询与回调

java - 为什么 Android Activity 中的方法回调必须是静态的?

javascript - 如何在 KOA 2 中编写异步中间件