简体   繁体   English

用承诺处理循环

[英]Handling loops with promises

I'm new to handling promises and I need to loop on their result value until I get the one I needed : 我是处理承诺的新手,我需要遍历它们的结果值,直到获得所需的值:

let index = 0;
while(!flag) // loop until result inside the promise is equal to "something"
{
    funcReturningPromise(index).then((result)=>{
        if(result === "something"){
            doSomething(result);
            flag = 1; // How can I send this result back to my function so I can stop looping ?
        }
        index++;
    });
}

How can I get a "callback" so that I can stop looping once I have the promise I wanted ? 我如何获得“回调”,以便一旦有了想要的承诺就可以停止循环播放? (I know that) (我知道)

Thanks in advance 提前致谢

If you have ECMAScript 2017 available, you can achieve this with async functions : 如果您有可用的ECMAScript 2017,则可以使用异步功能来实现:

async function waitForFlag() {
    let index = 0;
    while(!flag) // loop until result inside the promise is equal to "something"
    {
        const result = await funcReturningPromise(index);
        if(result === "something"){
            doSomething(result);
            flag = 1;
        }
        index++;
    }
}

(Obviously you then could also use break to exit the loop) (显然,然后您也可以使用break退出循环)

Like @Occam'sRazor mentioned in comment, it is not quite possible, atleast using regular loops anyways. 就像在评论中提到的@ Occam'sRazor一样,这是不可能的,至少要使用常规循环。

const getSomething = (index, callback) => 
  funcReturningPromise(index)
    .then(result => 
      result === 'something' ? callback(index) : getSomething(index++, callback)
    .catch(() => getSomething(index++, callback))

getSomething(0, doSomething)

HTH, written from top of my head. HTH,写在我头顶上。

Although it seems like a horrible thing to do, as your application might end up in an infinite loop, you can still achieve this using a recursive function 尽管这样做似乎很可怕,但是由于您的应用程序可能会陷入无限循环,因此您仍然可以使用递归函数来实现此目的

function myfunc() {
   checkTillSuccess(0);
}

function checkTillSuccess(flag) {
   if(!flag) {
      funcReturningPromise(index).then((result)=>{
        if(result === "something"){
            doSomething(result);
            checkTillSuccess(1)
        }
      }).catch(() => {
          checkTillSuccess(0)
      });
   }
}

As I stated in the comments, you can't do that with a regular loop because a regular loop is synchronous and promises are not. 正如我在评论中所述,您不能使用常规循环来执行此操作,因为常规循环是同步的,而promise不是。 You could use recursion to do some async "looping" though. 您可以使用递归来进行一些异步“循环”。

 let index = 0; (function recurse(callback) { funcReturningPromise(index).then((result) => { index++; console.log("did something with index "+index); if (index === 3){ // stop looping callback(); }else{ // keep looking recurse(callback); } }); })(function(){ // The looping has completed console.log("done looping"); }); function funcReturningPromise() { return new Promise(d => setTimeout(d, 1000)); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM