+ 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))
1 ответ
+ 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);