节点函数在promise.then()完成之前运行。

时间:2015-03-11 16:02:47

标签: node.js promise bluebird

foo完成后是否应该refreshToken运行?现在foo在foo完成之前运行。

function refreshToken() {
    var tokenFile = path.join(__dirname, 'token-file.json');
    return fs.readFileAsync(tokenFile, {encoding: 'utf-8'})
        .then(function(tokenString) {
            token = JSON.parse(tokenString);
        }).catch(function(err) {
            console.log("No token-file.json file found. " .red +
                "Please complete for a new one." .red);
            createTokenFile();
        }); 
} 

refreshToken();
foo();

1 个答案:

答案 0 :(得分:2)

Promise只是用对象包装的回调,它们仍然是异步的。你需要用.then()

包装你的foo调用
refreshToken()
.then(foo)

refreshToken()
.then(function(res){
  foo()
})

选择在很大程度上取决于foo()的实现方式。

相关问题