+ 1

How does this Javascript code works?

let promise = new Promise(function(resolve, reject) { resolve(1); setTimeout(() => resolve(2), 1000); }); promise.then(alert);//should not it be promise.then((message)=>alert(message))

29th Apr 2021, 4:09 PM
CŠ»aŠ²eŠ½ Š‚ŠµŃ€Š²ŠøŠ“Š°
CŠ»aŠ²eŠ½ Š‚ŠµŃ€Š²ŠøŠ“Š° - avatar
1 Answer
+ 3
It alerts with 1 immediately because only the first resolve or reject call matters in a Promise. The call to resolve(2) is ignored since the promise is already resolved at that point. In other words, your code's behaviour simplifies to: let promise = new Promise(function(resolve, reject) { resolve(1); }); promise.then(alert); or simplifies more to: alert(1);
30th Apr 2021, 6:03 PM
Josh Greig
Josh Greig - avatar