【问题标题】:Using recursive promise loops with thenthen 使用递归承诺循环
【发布时间】:2020-09-04 20:10:45
【问题描述】:

有一个 promise 返回下一个循环的参数。就像:

promise1(){
    return axios.get('https://google.com').then(result=>{
     if (result == someValue){ // continues
       promise1();
     }
     else { //if result does not equal this value, just break this loop and return
       return "stackoverflow";
     }})}

最后我想调用这个promise并在then之后做一些事情,它将是:

promise1().then(()=>{
//do something
})

但是,promise1 在我像上面那样调用此函数时在第一个循环中返回。我怎样才能等到else 块运行并返回“stackoverflow”?实际上,我明白为什么它会在第一个循环中返回,但我怎样才能让它在特定条件下返回呢?

【问题讨论】:

  • return promise1(); 在递归调用中
  • 那太快了 :) 有道理,你可以重写作为答案,我会标记的。非常感谢。

标签: javascript ecmascript-6 promise axios


【解决方案1】:

问题是当您从内部调用promise1() 时,它不会等待它(因为它是异步的)。相反,丢弃从内部调用返回的承诺并解析为undefined

同样要等待该调用,return 它来自 then 处理程序(then 将等待它,就像它被链接一样):

function promise1() {
  return axios.get('https://google.com').then(result => {
    if (result !== '') { // continues
      return promise1();
    } else { //if result does not equal this value, just break this loop and return
      return "stackoverflow";
    }
  })
}
promise1().then(console.log, console.error)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 2021-02-13
    • 2014-02-04
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    相关资源
    最近更新 更多