How to wait for promise in synchronous nodejs function?

Viewed 7796

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?

1 Answers
Related