Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise `then` with a function returning nothing vs with a function returning an another promise

I can't understand why we have such a strange result of execution this code.

Why isn't there an image of 12121212? And after each 1 we have three 2.

Promise.resolve()
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); })
.then(() => { console.log(1); return Promise.resolve(); });

Promise.resolve()
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); })
.then(() => { console.log(2); });
like image 398
Денис Степанов Avatar asked Dec 23 '22 19:12

Денис Степанов


1 Answers

It's because there are multiple ticks involved in resolving the promise with another promise.

But really, you should ignore this, and never rely on timings between independent chains of promises.

like image 128
Bergi Avatar answered Feb 05 '23 22:02

Bergi