简体   繁体   中英

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 :

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)

Like @Occam'sRazor mentioned in comment, it is not quite possible, atleast using regular loops anyways.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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