2017-08-08 136 views
1

我创建一个包含我的用户凭证的解密文件,使用异步方法:如何在同步nodejs函数中等待承诺?

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

+0

回报的承诺和'this.initUsers() 。然后...'? – Jorg

+0

你不能“同步等待承诺”。返回一个承诺,调用者使用'.then()'来承诺知道何时完成。 – jfriend00

+0

也许我在问错误的问题。而不是等待一个承诺,我可以突然摆脱诺言https://stackoverflow.com/questions/45571213/how-to-re-write-anync-function-to-be-synchronous –

回答

0

你必须做的

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

} 

你不能同步等待一个异步函数,你也可以尝试异步/ AWAIT

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

}