递归中的异步方法如何才能正确返回结果? [英] How can asynchronous method in recursion return result correctly?

查看:84
本文介绍了递归中的异步方法如何才能正确返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了有关如何循环运行异步方法的问题.我现在正在以类似递归的方式进行操作.

I asked question about how to run asynchronous method in loop. And I am now doing it in something like recursion.

如何按顺序执行循环中的异步方法?/a>

How can asynchronous method in loop executed in sequence?

但是,如果第二次成功获取数据库数据,现在我无法将数据传递给最终的回调(代码的最后一行).

But now I can't get data pass to final callback(last line of my code), if db data is fetched successfully at second time.

  1. 我注意到问题可能是:第二个CallGetDB resolve()我想要的数据,但第一个CallGetDB没有得到那个.然后,首先CallGetDB完成,解决所有问题.但是我不知道该怎么解决.

function CallGetDB(UID) {
      return new Promise(function(resolve, reject){
        GetDynamodb(UID)
        .then((data)=> {
                  console.log("check before if"+JSON.stringify(data));
                  dbResponse = data;
                  resolve(dbResponse);
                }
            )
        .catch((data)=> {
                if(index++ < 2)
                {
                  console.log("This is "+(index+1)+" try to get data from db with UID.");
                  setTimeout(function(){CallGetDB(UID);},100);
                }
                else
                {
                  console.log("Database multi fetch failed");
                  resolve("Database multi fetch failed");
                }
        });
  });

SendSQS(UID,event).then((data)=>{
    return CallGetDB(data);
 }).then((data)=>{
   console.log("I am at most out:" +JSON.stringify(data));
   response.body=JSON.stringify(data);
   callback(null,response);
 });

推荐答案

GetDynamodb(UID)包装在 new Promise 中是一种反模式,因为它返回了诺言

Wrapping GetDynamodb(UID) in a new Promise is an anti-pattern since it returns a promise.

以下操作会在默认情况下为 CallGetDB()添加一个 retries 参数,并在重试发生时在 catch()中返回一个新的Promise.在限制范围内....或引发新错误以陷入以下 catch()

Following adds a retries parameter with a default to CallGetDB() and either returns a new promise in the catch() when retries are within limits.... or throws a new error to get caught in following catch()

let sleep = ms => new Promise(r => setTimeout(r, ms));

function CallGetDB(UID, retries = 0) {

  return GetDynamodb(UID)
    .catch((data) => {
      if (retries++ < 2) {
        console.log("This is " + (retries + 1) + " try to get data from db with UID.");
        // return another promise
        return sleep(100).then(() => CallGetDB(UID, retries));

      } else {
        console.log("Database multi fetch failed");
        // throw error to next catch()
        throw new Error("Database multi fetch failed");
      }
    });
}


SendSQS(UID, event).then((data) => {
  return CallGetDB(data);
}).then((data) => {
  console.log("Data Success:" + JSON.stringify(data));
  response.body = JSON.stringify(data);
  callback(null, data);
}).catch(err => /* do something when it all fails*/ );

这篇关于递归中的异步方法如何才能正确返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆