JavaScript : 使用 Promise 调用递归函数 [英] JavaScript : Calling Recursive Functions With Promises

查看:90
本文介绍了JavaScript : 使用 Promise 调用递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:JavaScript

Language: JavaScript

递归 - 不是我最喜欢的话题.

Recursion - Not my Favorite Topic.

承诺 - 它们可能会让人困惑.

Promises - They can get confusing.

递归 + Promises - 我需要在一个带衬垫的房间里编程.

Recursion + Promises - I need to program in a padded room.

我制作了这个小小的 JS Fiddle 拼图,我称之为 The RecursiveFunHouse 作为保持理智的喜剧方式把问题简化成愚蠢的事情.希望你们能从我的痛苦中笑出来:)

I made this little JS Fiddle puzzle I call The RecursiveFunHouse as comedic way of keeping my sanity by simplifying the issue into something silly. Hopefully yall can get a laugh out of my pain :)

问题:

每次递归调用都依赖于前一次调用的结果,但为了获得结果,我必须运行一个异步任务并在其他子任务中使用该结果.

Each recursive call is dependent on the outcome of the previous call, but in order to get the outcome I must run an asynchronous task and use that outcome in other sub tasks.

递归趣味屋"帮助我将问题归结为这个问题 - 由于子任务仍在执行,原始递归循环继续使用未定义的值.

The Fun House - 循环收集 (-99) 和 99 之间的随机数.一旦最后一个数字和新数字之间的最后一个差异是正数,乐趣就结束了

The Fun House - loops around collecting random numbers between (-99) and 99. Once the last difference between the last number and the new number is positive the fun is over

打印Made it here 1...Made it here 6"应该表明子任务被正确处理并且我们有下一个循环的值.

Printing "Made it here 1...Made it here 6" should indicate that the sub-tasks were handled correctly and we have a value for the next loop.

当前它打印 1,2,3,6,4,5 :(

Current it prints 1,2,3,6,4,5 :(

recursiveFunHouse.js

var recursiveFunHouse = function(num){
    console.log("Made it here 1");
    var newNum = performSideTasks();

    console.log("Made it here 6");
    console.log("newNum");
    console.log(newNum);
    if(newNum-num >0 ){
            recursiveFunHouse(newNum);
    }
    else{
        console.log("The FunHouse Generated These Numbers :")
      for(var i = 0; i <numList.length; i++){
         console.log(numList[i]);
      }
    }

};

var performSideTasks = function(){
    console.log("Made it here 2");
    someAsyncTask().then(function(num){
            anotherTask(num);
      console.log("made it here 5");
      return num;
        });


}

var someAsyncTask = function(){
  return new Promise (function(resolve, reject) {
    console.log("made it here 3");
    var randNum = Math.floor(Math.random()*99) + 1; 
    randNum *= Math.floor(Math.random()*2) == 1 ? 1 : -1;   

    setTimeout(function() { 
      numList.push(randNum)
      resolve(randNum)
    }, 100);
  });
}




var anotherTask = function(num){
  console.log("made it here 4");
    console.log(num);

};

var numList= [];

recursiveFunHouse(20);

注意 - 请原谅我可悲的 return 语句 return num; 它只是显示了我希望我能告诉我的计算机的内容.

Note - Forgive my pathetic return statement return num; It just shows what I wish I could tell my computer.

关于递归和承诺的问题:

1) 首先,我是否应该担心进入​​下一个递归循环而承诺尚未解决?

1) Should I be worried in the first place about going into the next recursive loop with a promise not yet resolved?

2) 如果不是,有什么干净的方法可以保持这个函数分解并强制每个递归循环等待最后一次调用的解析?

2) If not, what is a clean way to keep this function decomposition and force each recursive loop to wait for the resolution of the last call?

递归和承诺有时看起来像巫师级 95 级的魔法……这就是我要说的.问题完成.

Recursion and Promises can seem wizard-level-95 magical sometimes... that's all I'm saying. Question-Done.

推荐答案

如评论中所述,您必须稍微修改 performSideTasks 使其返回 Promise:

As stated in the comment, you have to slightly modify performSideTasks to make it return the Promise:

var performSideTasks = function () 
{
  console.log( "Made it here 2" )
  return someAsyncTask().then( function ( num )
  {
    anotherTask(num);
    console.log("made it here 5")
    return num
  } )
} 

然后就可以在main函数的then()方法中使用异步结果.

Then you can use the asynchronous result in the then() method of the main function.

var recursiveFunHouse = function ( num )
{
  console.log( "Made it here 1" )
  performSideTasks().then( function ( newNum )
  {
    console.log( "Made it here 6" )
    console.log( "newNum" )
    console.log( newNum )
    if ( newNum-num > 0 )
    {
      recursiveFunHouse( newNum )
    }
    else
    {
      console.log( "The FunHouse Generated These Numbers :" )
      for( var i = 0 ; i <numList.length ; i++ )
      {
        console.log( numList[i] )
      }
    }
  } )
}

这篇关于JavaScript : 使用 Promise 调用递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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