我对这种异步行为感到困惑。
当 token
为 false
时,refreshToken()
函数运行但 createTokenFile()
不等待让它完成。
不应该 var tokenDate = new Date(token.expires);
在 callApiToken().then(function() {refreshToken();})
之后等待在执行之前完成?
function createTokenFile() {
console.log("No token-file.json file found. " .red +
"Please complete for a new one." .red);
return callApiToken().then(function() {
refreshToken();
});
}
function checkExpiredToken() {
return new Promise(function(resolve, reject) {
if (!token) {
refreshToken();
}
var tokenDate = new Date(token.expires);
var utc = new Date().toUTCString();
var now = new Date(utc);
}
function refreshToken() {
try {
var tokenFile = path.join(__dirname, 'token-file.json');
console.log(tokenFile);
return token = JSON.parse(fs.readFileSync(tokenFile, {encoding: 'utf-8'}));
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
} else {
return createTokenFile();
}
}
}
更新为 refreshToken()
最佳答案
Shouldn't
var tokenDate = new Date(token.expires);
wait aftercallApiToken().then(function() {refreshToken();})
to finish before executing?
不 - 它不在等待 promise 解决的 .then()
回调中。它只等到创建 promise - 但 promise 解决(您称之为“完成”)是异步的。请注意, promise 不是魔法,它们是 just callbacks .
要修复您的代码,
- 在
createTokenFile
中,您需要从then
回调中返回
refreshToken()
checkExpiredToken
应该 not use thePromise
constructorrefreshToken
应该总是返回一个 promiserefreshToken
没有理由同步读取文件- 你不应该将
token
缓存为包含值的全局变量
function createTokenFile() {
console.log("No token-file.json file found. " +
"Please complete for a new one.");
return callApiToken();
}
function checkExpiredToken() {
return (tokenPromise || refreshToken())
.then(function(token) {
var tokenDate = new Date(token.expires);
var utc = new Date().toUTCString();
var now = new Date();
});
}
function refreshToken() {
var tokenFile = path.join(__dirname, 'token-file.json');
console.log(tokenFile);
return tokenPromise = readFileAsync(tokenFile, {encoding: 'utf-8'}))
.then(JSON.parse)
.catch(function(err) {
if (err.code !== 'ENOENT') {
throw err;
} else {
return createTokenFile().then(refreshToken);
}
});
}
(其中 readFileAsync
是 fs.readFile
的 promisified 版本)
关于javascript - Node.js Promise - 代码不应该等到 .then 完成()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954684/