承诺递归 [英] Promise with recursion

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

问题描述

我已经看过几个关于promises中递归的问题,并对如何正确实现它们感到困惑:

I've taken a look at a few questions on recursion in promises and am confused on how to implement them properly:

  • Recursive Promise in javascript
  • AngularJS, promise with recursive function
  • Chaining Promises recursively
  • Javascript Recursive Promise

我把一个简单的例子放在一起(见下文) - 这只是一个例子,所以我可以理解如何使用promises工作进行递归,而不是我正在工作的代码的表示。

I put together a simple example (see below) - this is just an example so I can understand how to make recursion with promises work and not a representation of the code in which I'm working.

Net-net,I我希望得到解决的承诺,但根据出来放在节点上,它没有解决。有关如何解决问题的任何见解?

Net-net, I'd like the promise to resolve, but according to the output on node, it doesn't resolve. Any insight into how to make this resolve?

var i = 0;

var countToTen = function() { 
    return new Promise(function(resolve, reject) {
        if (i < 10) {
            i++;
            console.log("i is now: " + i);
            return countToTen();
        }
        else {
            resolve(i);
        }
    });
}

countToTen().then(console.log("i ended up at: " + i));

控制台上的输出:

> countToTen().then(console.log("i ended up at: " + i));
i is now: 1
i is now: 2
i is now: 3
i is now: 4
i is now: 5
i is now: 6
i is now: 7
i is now: 8
i is now: 9
i is now: 10
i ended up at: 10
Promise { <pending> }

承诺永远不会解决。

推荐答案

如果你看代码只要 i 小于10你就会递归而永远不会解决这个承诺。你最终解决了一个承诺。但这不是初始来电者的承诺。

If you look at your code as long as i is less than 10 you are recursing and never resolving the promise. You eventually resolve a promise. but it is not the promise the initial caller gets.

您需要使用递归返回的承诺来解决。如果您使用承诺解决该系统的工作原理,它仍然无法解决,直到该值得到解决:

You need to resolve with the promise returned by the recursion. How the system works if you resolve with a promise it will still not resolve until also the value is resolved:

let i = 0;
const countToTen = () => new Promise((resolve, reject) => {
    if (i < 10) {
      i++;
      console.log("i is now: " + i);
      resolve(countToTen());
    } else {
      resolve(i);
    }
  });

countToTen().then(() => console.log("i ended up at: " + i));

最后一部分也有错误。你没有提供一个函数然后所以如果你做了一些实际上已经等待的东西你就得到了我最终得到了:首先是0

There was an error in the last part as well. You didn't provide a function to then so if you would have done something that actually would have waited you would have got the "i ended up at: 0" first.

这篇关于承诺递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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