idevosm
idevosm

Reputation: 45

Will Second Promise wait for the First Promise to complete Before it start

So I am working on a project after learning promise for some time ago, I needed it in my current project, but I was bluffed by the result am getting.

I have two promises, promise1 and promise2, in promise1 I have some kind of loops and loading of data, in promise2 I have another logic which doesn't rely on the completion of the promise1 to execute. So, since promise is the best way of handling these two executions differently based on my understanding, it means that promise1 don't have to complete before promise2 starts, or am I wrong, because from my result, I can see that promise1 has to complete before promise2 starts, but every other code in the file executes without waiting for the promises to complete which is good.

If this is the default behavior of promise, then I will need to know how make the two promises to run asynchronously without depending on each other.

Here is my code example below

let promise1 = new Promise((res, rej) =>{
    for(let i = 0; i < 52435435; i++){

    }
    res('done')
});

let promise2 = new Promise((res, rej) => {
    res('Done second')
})

promise1.then(txt => console.log(txt))
promise2.then(txt => console.log(txt))

console.log('Last console')

result

Last console
app.js:12 done
app.js:13 Done second

Upvotes: 0

Views: 207

Answers (1)

AvivS
AvivS

Reputation: 74

You have to read about JS workers pool. Your for loop not give any other task chance to get some cpu. Use setTimeout to simulate an async process!

Upvotes: 2

Related Questions