承诺链中类似递归的行为
Recursion-like behaviour in a Promise chain
我目前正在努力实现递归到特定的承诺块。
我将我的代码抽象为以下内容以提供一个示例:
function x(){
return new Promise((resolve, reject)=>{
return resolve(2)
})
}
var testvar = 0
x()
.then(result => {
// simulating mongodb request which returns another promise
return new Promise(resolve => {resolve()})
})
.then(result => { // BLOCK START
// simulating another operation
testvar += 1
return new Promise(resolve => {resolve()})
})
.then(result => {
// some other operations
if(testvar < 2){
// RERUN PROMISE FROM BLOCK START
console.log("pls recurse")
}else{
// some other operation
return new Promise(resolve => {resolve()})
}
// BLOCK END
})
.then(result => {
// continue
console.log("foo")
})
.catch(err => console.log(err))
// classic approach
function y(){
// something
// Operation 1
// Operation 2
if(x != 1 ){
y() // recurse
}else{
// continue
}
}
现在我想要这段代码做的是一个接一个地运行承诺链,直到最后一个(记录"foo"的那个)。除非testvar小于2,否则我希望再次执行Function from "//BLOCK START",直到testvar大于或等于2。
我依靠这个基于承诺的构建,因为我正在对helper库和返回承诺的mongodb进行一些异步函数调用。
代码也可以在
中进行测试。如果有什么不清楚的地方,请随时提问——我很乐意尝试准确地回答我的问题。谢谢你的帮助。
与普通递归函数没有太大区别。您将代码移动到runBlock
函数中,并且在if
条件下,您可以再次调用return runBlock(result);
或返回已解决的承诺:
function x() {
return new Promise((resolve, reject) => {
return resolve(2)
})
}
var testvar = 0
function runBlock(result) {
testvar += 1
return new Promise(resolve => {
resolve()
})
.then(result => {
// some other operations
if (testvar < 2) {
console.log('testvar < 2');
// RERUN PROMISE FROM BLOCK START
return runBlock(result);
} else {
console.log('testvar >= 2');
// some other operation
return new Promise(resolve => {
resolve()
})
}
// BLOCK END
})
}
x()
.then(result => {
// simulating mongodb request which returns another promise
return new Promise(resolve => {
resolve()
})
})
.then(runBlock)
.then(result => {
// continue
console.log("foo")
})
.catch(err => console.log(err))
function a(a) {
return new Promise(resolve => {
resolve(a)
})
}
// classic approach
function y() {
// something
// Operation 1
// Operation 2
if (x != 1) {
y() // recurse
} else {
// continue
}
}
这可能是@t的简化版本。Niese在承诺中的递归。可以这样做:
var pr = Promise.resolve(1),
fulFillment = v => Promise.resolve(v*=2)
.then(v => v > 100 ? "foo" : (console.log(v), fulFillment(v)));
pr.then(fulFillment)
.then(v => console.log(v))
.catch(e => console.log(e));
相关文章:
- 递归承诺调用 - 内存范围变量问题
- JavaScript 中的递归承诺
- 蓝鸟递归承诺未得到解决/实现
- 多个条件异步递归函数和 jQuery 承诺
- 使用承诺的异步递归
- 如何递归调用承诺函数
- 使用承诺以递归方式检索分页数据
- 承诺的递归函数不会触发返回语句
- 理解递归函数的节点.js中的承诺
- ES6/When.js-在递归承诺链中处理承诺解析
- 将递归承诺的结果添加到数组中
- 使用递归函数的承诺
- 在递归中使用javascript承诺进行Api调用
- 带有承诺的Javascript递归函数
- Bluebird的递归承诺没有返回
- 递归承诺链末端的链式动作
- 生成一个依赖于递归承诺的承诺
- Javascript递归承诺陷入无限循环
- 如何解决递归承诺
- 使用递归承诺来阻止内存泄漏