JavaScript Promise

Last Updated On Monday 4th Oct 2021

Promise

  • ES6’s new solution for asynchronous programming in JS
  • Syntactically: Constructor
  • Functionally: The promise object is used to encapsulate an asynchronous operation and get its success/failure result value

Asynchronous

File Operation using fs

	require("fs").readFile("./app.html", (err, data) => {

});
	

AJAX

	$.get("/server", (data) => {

});
	

Why Use Promise

  • Support chain call, which can solve callback hell
  • The way to specify the callback function is more flexible

Generate random integers

	function rand(a, b) {
  return Math.ceil(Math.random() * (b - a + 1)) + a - 1;
}
	

The three States of Promise

A property in the promise instance object PromiseState.

  • pending: undecided
  • resolved /fulfilled: successful
  • rejected: failed

Promise.reject()

	new Promise((resolve, reject) => {
    reject()
})
	

Promise.resolve()

	new Promise((resolve, reject) => {
    resolve()
})
	

Promise.all([promise1, promise2, promise3])

  • The waiting principle is executed after all promises are completed.
	Promise.all([promise1, promise2, promise3]).then((values) => {
  // values is an array, will collect the results of the previous promise values[0] => the successful results of promise1
})
	

The value of the promise object
Another property of the promise instance object PromiseResult.

Holds success/failure the result of the asynchronous operation of the object

  • resolve
  • reject