我拥有这些函数的目的是通过 api 调用检索 token 。如果用户输入错误的密码,promise 将拒绝,并且在拒绝时再次调用该函数以让用户再次尝试。
如果用户第一次输入正确的密码,就没有问题。
但是,如果用户输入错误的密码并重试...但重试成功,则说明我遇到了内存问题。由于第二次尝试时递归调用了 callApiToken()
,promise 已完成,并且 callApiToken().then(function() {freshToken(); })
被调用。 file.token = JSON.parse(tokenString);
已完成,但在不同的内存范围中。不知道该怎么办。我这样说是因为例程运行成功。但全局 var 文件
并未按应有的方式填充。
createTokenFile()
首先被调用。
var file = {};
function createTokenFile() {
block = true;
callApiToken()
.then(function() { refreshToken(); }) // ON THE SECOND RECURSIVE
.catch(function() { // RUN refreshToken() IS CALLED
callApiToken();
}).finally(function() {
block = false;
});
}
function refreshToken() {
var tokenFileAbsolute = path.join(__dirname, 'token-file.json');
return fs.readFileAsync(tokenFileAbsolute, {encoding: 'utf-8'})
.then(function(tokenString) {
file.token = JSON.parse(tokenString);
}).catch(function(err) {
console.log("No token-file.json file found. " .red +
"Please complete for a new one." .red);
createTokenFile();
});
}
更新与其他 promise 代码,为callApiToken()
提供解析,这实际上是getCredentials
:
注意:fs.writeFileAsync(tokenFile, token)
在第二次递归调用时成功完成。
function getPassword(user) {
return readAsync({prompt: "Password: ", silent: true, replace: "*" })
.then(function(pass) {
return postAsync(URL, payload(user[0], pass[0]));
});
}
function getCredentials() {
return readAsync({prompt: "Username: "}).then(getPassword);
}
function writeToFile(data, response) {
tokenFile = path.join(__dirname, 'token-file.json');
token = JSON.stringify({
id: data.access.token.id,
expires: data.access.token.expires
});
return fs.writeFileAsync(tokenFile, token).then(function(err) {
if (err) throw err;
console.log("Token was successfully retrieved and written to " .cyan +
tokenFile .cyan + "." .cyan);
});
}
最佳答案
不存在“内存范围”这样的东西。您只是遇到了时间问题!
如果操作是异步的,当您想要等待结果时,您总是必须从函数返回
一个 promise - 而且您似乎确实这样做了。
var file = {};
function createTokenFile() {
block = true;
callApiToken()
.then(function() {
return refreshToken();
// ^^^^^^ here
})
.catch(function() {
return callApiToken();
// ^^^^^^ and here
}).finally(function() {
block = false;
});
}
function refreshToken() {
var tokenFileAbsolute = path.join(__dirname, 'token-file.json');
return fs.readFileAsync(tokenFileAbsolute, {encoding: 'utf-8'})
.then(function(tokenString) {
file.token = JSON.parse(tokenString);
}).catch(function(err) {
console.log("No token-file.json file found. " .red +
"Please complete for a new one." .red);
return createTokenFile();
// ^^^^^^ and here!!!
});
}
顺便说一句,我的猜测是你的递归有缺陷。您不希望 refreshToken
拒绝,并且 createTokenFile
从自身内部调用自身(而不是第二个 callApiToken()
)吗?
关于javascript - 递归 Promise 调用 - 内存范围变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29021783/