Yuri Molodyko
Yuri Molodyko

Reputation: 600

How to break while inside promise.then?

I wanna exit from the loop, after check my data in Promise.then. How can i do it? Now i have infinity loop.Here is the code:

    let my_break = 0
    let page_id = 1
    let p = Promise.resolve()
        while(my_break===0) {
            p = p.then(() => { 

                getReposData(name,page_id).then(data=>{
                    if (data.length===0){
                        my_break = 1
                    }
                   else {

                    data.forEach(item=>{createReposLink(item,parent_el)})

                   }
                })
                page_id += 1
            });

        }

Upvotes: 0

Views: 592

Answers (2)

foobar2k19
foobar2k19

Reputation: 84

Promises are inherently asynchronous, which means the earliest point at which your then callback will be executed will be the next event tick. Your while loop is executing on the current event tick, and will not relinquish execution control until it's finished. It will only finish when the promise resolves, which can only happen on the next event tick, which cannot happen until your loop finishes; which is never.

There is no thread.sleep in javascript; if you want to pause execution while an async operation is running, you'll need to queue up the rest of your code to run after the promise resolution.

If you look at the promise spec, returning a promise from a then callback will extend the wait of the original promise.

let p = getReposData(name, page_id).then(data => {
  if (data.length === 0){
    return;
  }
  return Promise.all(data.map(item=> createReposLink(item, parent_el)))
})

Upvotes: 1

niccord
niccord

Reputation: 844

I would definitively reach for async/await, like this:

let my_break = 0
let page_id = 1
while (my_break===0) {
    const data = await getReposData(name, page_id)
    if (data.length===0){
        my_break = 1
    } else {
        data.forEach(item=>{createReposLink(item,parent_el)})
    }
    page_id += 1
}

you can find more about async/await here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Upvotes: 1

Related Questions