如何知道什么时候递归,异步任务完成 [英] How to know when a recursive, asynchronous task finishes

查看:105
本文介绍了如何知道什么时候递归,异步任务完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步功能,即可以递归到自身。

I have a async function, which can recurse into itself.

我在每个函数运行时间增加的jQuery deferreds到一个数组,一个使用 $。当()来检查是否所有的承诺都解决了。我的问题是,我似乎无法做到这一点没有arbitary超时,因为我根本不知道什么时候停止功能递归和增加新的承诺。

I'm adding jQuery deferreds to an array each time the function runs, an use $.when() to check if all promises have resolved. My issue is that I can't seem to do this without an arbitary timeout, as I simply don't know when the function stops recursing and adding new promises.

  • Here's a JSBin demonstration.
  • And here's the real world example.

推荐答案

不要推到承诺只有同步,让你知道当你完成。由于你的函数是递归,并返回一个承诺,你可以使用这个递归调用的结果的承诺。使用 $。当()只为结果的的电流的递归级别,而不是调用堆栈的所有承诺。

Do push to promises only synchronously, so that you know when you are finished. Since your function is recursive and returns a promise, you can just use the result promises of the recursive calls for this. Use $.when() only for the results of the current recursion level, not for all promises in the call stack.

还检查我的回答了解承诺在node.js中的递归函数并的Is有使用原始Q承诺库节点递归遍历目录异步的例子 - 即使他们没有使用jQuery的实现,他们应该给你一个想法如何做到这一点。

Also check my answers to Understanding promises in node.js for recursive function and Is there an example of using raw Q promise library with node to recursively traverse a directory asynchronously? - even though they're not using jQuery's implementation, they should give you an idea of how to do it.

这篇关于如何知道什么时候递归,异步任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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