承诺链中类似递归的行为

Recursion-like behaviour in a Promise chain

本文关键字:递归 承诺      更新时间:2023-09-26

我目前正在努力实现递归到特定的承诺块。

我将我的代码抽象为以下内容以提供一个示例:

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));