I am quite new with Promises and want to know why is it that my Promise definition gets executed without me calling a .then()
or resolve on it.
var promise = new Promise(function (resolve, reject) {
console.log("Starting loader");
resolve();
});
If you run the sample and see the console you will see the 'Starting loader' message.
https://jsfiddle.net/npqgpcud/
The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error).
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.
Define an async function. Use the await operator to await the promise. Assign the result of using the await operator to a variable.
A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending.
If any of the promises reject or execute to fail due to an error, all other promise results will be ignored. Let's create three promises to get information about three Pokémons.
Tips for Signing an Executory Promise An executory promise, also known as an executory contract, takes place when two parties agree to a certain set of terms and conditions that are to be fulfilled at some point in the future.
The.then () method should be called on the promise object to handle a result (resolve) or an error (reject). It accepts two functions as parameters. Usually, the.then () method should be called from the consumer function where you would like to know the outcome of a promise's execution.
A Promise uses an executor function to complete a task (mostly asynchronously). A consumer function (that uses an outcome of the promise) should get notified when the executor function is done with either resolving (success) or rejecting (error).
That is simply how promises are defined. They run their executor function immediately. It's in the spec: Promise(executor), step 9.
This is an instance of the revealing constructor pattern; reading that might help you understand.
That occurs because a promise will execute immediately and synchronously.
.then()
add functions that will be executed when the promise is either fulfilled (resolve
argument) or rejected (reject
argument).
with info from comments by @Kirill Slatin
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