Promises makes asynchronous code easier to understand
The idea with Callback methods is that you pass the callback method into an asynchronous call and once the call has completed it calls the callback method.
Promises are a more elegant way of dealing with asynchronous calls.
Promises declare how some processing will be done. It has 3 states:
Pending - initial state
Resolved - this occurs after the operation has completed
Rejected - this occurs when there is an error during execution
Promises can be chained together. They simplify the code required for asynchronous method calls.
NodeJs is a runtime environment for running JavaScript outside a browser and on the server side.
Our examples use NodeJS as it is easier to execute as no web page wrapper is required to run the JavaScript - makes examples easier.
If you do not have NodeJS installed please follow instructions to install and run it:
You can see examples below.
Alternatively clone the code from github:
git clone https://github.com/spotadev/javascript-examples.git
Once cloned you can find the promise examples under a folder called "promises".
To run the examples type:
node promise.js
node promise_using_async_await.js
node chain_promises.js
node chain_promises_return_promises.js
// This is a simple example of a promise
//
// To run type:
//
// node promise.js
//
// The output is:
//
// Promise resolved successfully
//
const promise = new Promise(function (resolve, reject) {
const string1 = "node is cool";
const string2 = "node is cool";
if (string1 === string2) {
resolve();
} else {
reject();
}
});
promise
.then(function () {
console.log("Promise resolved successfully");
})
.catch(function () {
console.log("Promise is rejected");
});
// the async and await keywords are an alternative way of using Promises.
//
// To run type:
//
// node promise_using_async_await.js
//
// Output is:
//
// Error: Strings are not same
//
const helperPromise = function () {
const promise = new Promise(function (resolve, reject) {
const x = "node is cool";
const y = "node is VERY cool";
if (x === y) {
resolve("Strings are same");
} else {
reject("Strings are not same");
}
});
return promise;
};
async function demoPromise() {
try {
let message = await helperPromise();
console.log(message);
} catch (error) {
console.log("Error: " + error);
}
}
demoPromise();
// Note that "then" returns another promise
//
// Note that we purposely add an undefined variable called doesNotExist
// which triggers an error. This error is caught in the catch
//
// To run type:
//
// node chain_promises.js
//
// Output is:
//
// 1
// 2
// Promise is rejectedReferenceError: doesNotExist is not defined
//
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) { // (**)
console.log(result); // 1
return result * 2;
}).then(function(result) { // (***)
console.log(result); // 2
return doesNotExist
}).then(function(result) {
console.log(result); // fails to print
}).catch(function (e) {
console.log("Promise is rejected: " + e);
});
// This example creates and returns Promises
//
// To run type:
//
// node chain_promises_return_promises.js
//
// Output:
//
// 1
// 2
// 4
//
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
}).then(function(result) {
console.log(result); // 1
return new Promise((resolve, reject) => { // (*)
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) {
console.log(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) {
console.log(result); // 4
});
Back: JavaScript
Page Author: JD