我目前正在努力实现特定 Promiseblock 的递归。
我将代码抽象为以下内容以提供示例:
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
}
}
现在我想要这段代码做的是一个接一个地运行 Promisechain,直到最后一个(记录“foo”的那个)。除非 testvar 小于 2,否则我希望再次执行“//BLOCK START”中的函数,直到 testvar 大于或等于 2。
我依赖于这个基于 Promise 的构建,因为我正在对辅助库和返回 Promise 的 mongodb 进行一些异步函数调用。
代码也可以在fiddle中进行测试
如果有不清楚的地方,请随时提问 - 我很乐意尝试准确地表达我的问题。 感谢您的帮助。
最佳答案
与普通的递归函数没有太大区别。您可以将代码移至 runBlock
函数中,并在 if
条件下再次调用 return runBlock(result);
或返回您已决的 promise :
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
}
}
关于javascript - Promise 链中类似递归的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38999969/