首页 > 解决方案 > 递归调用的异步函数将未定义返回给被调用函数

问题描述

我从另一个异步锁定代码中调用了一个异步函数。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)
                }
            }
        }

标签: javascriptnode.jsrecursionasync-await

解决方案


正如@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) }) }


推荐阅读