I want do a sync task and have tried something like the code bellow, It isn't same what I thought about the Promise before, can you explain this one for me?
var p2 = new Promise((resolve, reject) => {
console.log('Promise 2');
resolve();
});
var p1 = new Promise((resolve, reject) => {
console.log('Promise 1');
resolve();
});
Promise.all([p1]).then(p2);
It always output the "Promise 2" before "Promise 1".
When you call new Promise
, the function you pass into it (the promise executor) is run immediately, before you receive the promise back and store it in your variable. The reason for that is that the promise executor function's job is to start an asynchronous process. It can't start it if it isn't called. That's why you see "Promise 2" before "Promise 1", because that's the order you're calling new Promise
.
Also note that Promise.all
doesn't start anything. It just watches the processes that are already in progress and reports on the outcome.
Here's a more realistic use of new Promise
that may help you understand the timing of things: Starting a timer and resolving the promise when the timer fires:
function timer(ms, value) {
return new Promise(resolve => {
console.log(`promise executor called for value "${value}"`);
setTimeout(() => {
console.log(`timer completed for value "${value}", resolving promise`);
resolve(value);
}, ms);
});
}
// Note that I never do anything with the promise `timer` returns
// here, but since it's already started by the time
// it returns, it still does something
console.log("creating anonymous");
timer(800, "anonymous");
console.log("creating p1");
const p1 = timer(1600, "p1");
console.log("creating p2");
const p2 = timer(2400, "p2");
console.log("calling Promise.all([p1, p2])");
Promise.all([p1, p2])
.then(results => {
console.log(`Promise.all promise reseolved with "${JSON.stringify(results)}"`);
})
.catch(error => {
// Normally you'd handle errors here, it's just
// that the promsies from `timer` are never rejected
});
.as-console-wrapper {
max-height: 100% !important;
}