Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for promise in synchronous nodejs function?

I create a decrypted file containing my users credentials, using an async method:

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

            });

  },

I call that function from a sync method. And then I need to wait for it to complete before the sync method continues.

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

The console.log executes before this.initUsers(); finishes. How can I make it wait instead?

like image 797
Dingredient Avatar asked Aug 15 '26 14:08

Dingredient


1 Answers

You would have to do

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

}

you can't wait synchronously for a asynchronous function, you can also try async/await

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

}
like image 121
marvel308 Avatar answered Aug 18 '26 05:08

marvel308



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!