javascript - 递归调用的异步函数将未定义返回给被调用函数
问题描述
我从另一个异步锁定代码中调用了一个异步函数。asyn 函数进行了一个关键的 API 调用,因此我需要使用重试逻辑来尝试执行它两次。运行两次后它应该会中断。
我的代码实现正确地中断了递归,但问题是在第二个异步函数可以在异步锁中执行被调用的方法之前得到未定义的响应,因此破坏了锁。第二个 API 调用的响应发生在锁之外。代码如下:
//Callee function:
return new Promise((resolve, reject) => {
lock.acquire('Block_key', () => {
if(shouldRefresh()){
return getApiCall(
config,
flow,
retryCount
)
.then((response) => {
//debugger;
// Getting a undefined response
return resolve('Generated Success');
})
.catch((err) => {
return reject(err);
})
} else{
global.logger.info(`Returned from Cache.`);
// Remove cannot log token
global.logger.info(JSON.stringify(result));
return resolve(result);
}
},opts).then((response) => {
//debugger;
return resolve(response);
})
.catch((err) => {
return reject(err);
})
});
//Recursive Async function
const getApiCall = async function(config,flow, retryCount){
const hrstart = process.hrtime();
try{
let result = await _ouath2.getToken(util.getTokenConfig(config, flow,_scope)); // making the API call
let newResult = util.adjustExpiration(result, _refreshBufferTime);
_token = _ouath2.token.create(newResult);
return _token;
} catch(err){
if(retryCount === 1){ // hreaking the recursion
_log('Failed enough... Quitting now');
return err;
}else{
setTimeout(() => {
getApiCall(config,flow, retryCount-1); // making the recursive call
}, 3000)
}
}
}
解决方案
正如@Adam 在评论中指出的那样,我做错了在递归块中进行调用时没有返回任何内容。请注意,来自异步函数的响应只能是一个 Promise,因此,对该函数的调用是在一个新的 Promise 块中进行的,并被解决/拒绝。这发送了正确的响应而不是未定义的响应。正确的代码是:
if(retryCount === 1){
抛出错误;// 这里抛出错误很重要 }else{ return new Promise((resolve, reject) => { setTimeout(() => {
getApiCall(config,flow, retryCount-1).then((response) => { return resolve(response); }).catch((err) => { global.logger.info('Error'+err); return reject(err); })
}, 1000) }) }
推荐阅读
- apache-spark - Dataproc 无法解压缩由 AWS Kinesis 压缩的 .gz 文件
- c# - 从 Windows/ 控制台应用程序中的 WEB API 响应中获取流数据
- sql - SQL OPENJSON - 解析 JSON 数组
- spring - 无法从 logback 在 logstash 中设置 attrs
- firebase - Firebase 存储超出配额限制
- java - 在 Maven 范围内,gradle 的 compileOnly 是什么?
- javascript - 如果在同一组件上,Angular router.navigate 不会路由到解析器
- spring-boot - 让 Reactor Kafka 消费者保持活力
- openssl - 为什么在 MacOS Catalina 上使用 Cro 时 Raku 会因“中止陷阱:6”而崩溃?
- asp.net-core - Razor 页面的 ASP.NET Core 3.1 路由