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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With