About
Data Concurrency - Promise in the Javascript context
A promise is a function that encapsulate a executor function in order to:
- execute it asynchronously
- and returns its result (ie fulfillment)
A promise is one way of enabling asynchrony in Javascript.
ajax function returns generally a promise.
Articles Related
Concept
Syntax
The promise mechanism has two syntax:
Creation
The creation of a promise starts immediately an encapsulated function called the executor asynchronously (ie started in other thread)
Example:
- with the chaining constructor
promise = new Promise( executor(resolve, reject) ) )
- with the async keyword
promise = async executor
Executor
The executor function is the function started at the creation of the promise.
With:
- the chaining syntax, you pass the executor to the chaining constructor and it must two functions as argument:
- resolve to resolve the promise
- reject to pass an error
- the await/async syntax, you create an Javascript - Await and Async Syntax with the async keyword.
- return a value to resolve it
- or throw an error
State
A promise may be in three state:
- pending - this is the start state (ie when the final value is not available yet)
- then:
- resolved (ie fulfilled) - via the resolve function that associate a value to the promise.
- or rejected via the reject function or when an error prevented the final value from being determined.
Little demo to see the state (this demo must be run in the devtool via F12)
// Promise already resolved to go quick
var resolvedPromisesArray = [Promise.resolve(1), Promise.resolve(2)];
// Try to resolve them again
var p = Promise.all(resolvedPromisesArray);
// immediately logging the value of p should show a pending state
console.log(p);
// using setTimeout we can execute code later
setTimeout(function() {
console.log(p); // should show a pending resolved
});
Resolve
Resolve is a in the context of a promise means that the execution of the executor function has ended without error and has returned a value.
It's also the name of the function that is:
- passed as first argument to the chaining executor function.
- used to:
- send the value back to the promise
- and change the promise state to resolve
Example and Snippet of the executor
executor(resolve, reject) => {
if (allGood) {
resolve(someValue); // The promise is resvoled (ie fulfilled) - The value may be of any type, including undefined.
} else {
reject("failure reason"); // rejected - The value may be any type, including undefined, though it is generally an Error object, like in exception handling.
}
}
Fulfillment
Once the executor function has been executed (fulfilled), you can retrieve either:
- a value
- or an error
Get the value
- chaining: see Javascript - Promise Chaining
- await/aysnc: the return value of the executor
Get the error
- chaining: see Javascript - Promise Chaining
- await/aysnc: with a try/catch block
Lifecycle Example
with the async/await syntax
fn = async function (i) {
console.log("Promise "+i+" was started");
return i+1;
};
(async () => {
promises = []
console.log("Creation of the promises");
for (var i = 0; i < 5; i++) {
promises.push(fn(i));
};
console.log(" ");
console.log("We got back promises object");
for (var i = 0; i < promises.length; i++) {
console.log(promises[i].constructor);
};
console.log(" ");
console.log("We unwrap the promise and get the result");
for (var i = 0; i < promises.length; i++) {
console.log(await promises[i]);
};
console.log(" ");
})();