I create two promises, but I do not run the then method on those promises. Yet once the promise objects go out of scope, the promise code runs as if .then
was called.
How is a Promise
settled without a call to the .then
method?
I am asking because I would like to load an array with Promise
objects and then run the promises in sequence.
function promises_createThenRun() {
const p1 = createPromise1();
const p2 = createPromise2();
console.log('before hello');
alert('hello');
console.log('after hello');
// the two promises run at this point. What makes them run?
}
function createPromise1() {
let p1 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 1');
resolve();
}, 2000);
});
return p1;
}
function createPromise2() {
let p2 = new Promise((resolve, reject) => {
window.setTimeout(() => {
console.log('timer 2');
resolve();
}, 1000);
});
return p2;
}
The then() method returns a Promise . It takes up to two arguments: callback functions for the success and failure cases of the Promise .
The code inside the Promise constructor runs when the promise is created and it runs synchronously which surprises some people. So even without then() everything still runs.
then() takes two arguments, a callback for success and another for failure. Both are optional, so you can add a callback for success or failure only.
The only thing to understand is that once resolved (or rejected), that is it for a defered object - it is done. If you call then(...) on its promise again, you immediately get the (first) resolved/rejected result. Additional calls to resolve() will not have any effect.
The code inside the Promise constructor runs when the promise is created and it runs synchronously which surprises some people. So even without then()
everything still runs.
new Promise(resolve => console.log("running"))
Code in the callback for the setTimeout
however, doesn't run until it's called, but it too will run even without the then()
new Promise(resolve => {
console.log("promise created")
setTimeout(() => console.log("this runs later"), 1000)
})
When calling .then
you just set up a "callback" which says what should happen after the promise is done. So the promise will be called, with or without declaring such callback.
Imagine the promise that calls a AJAX request. Calling .then
and passing a function to it will make it run when the ajax call was finished (successfully or not as in timeout or other errors). But not calling .then
will not stop the request to be run. You will simply not react to the results of the request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With