JavaScript PromiseJavaScript Promise

JavaScript Promises are used to track the state of an asynchronous task.

1
new Promise(/* executor */ function(resolve, reject){...});

Promise states

  • fulfilled - the action relating to the promise successed
  • rejected - the action relating to the promise failed
  • pending - hasn’t fulfilled or rejected yet
  • settled - has fulfilled or rejected

A promise can be resolved to either a promise or thenable, in which case it will store the promise or thenable for later unwrapping.

how to create a promise

1
2
3
4
5
6
7
8
9
var promise = new Promise(function(resolve, reject){
//process a task, possibly async, then...
if(/* task successed */){
resolve("it worked!");
}
else{
reject(Error("it failed!"));
}
})

how to use promise

1
2
3
4
5
promise.then(function(result){
console.log(result); // "it worked!"
}, function(err){
console.log(err); //"it failed!"
});

then() takes two arguments, callback for a success case, and another for the failure case. Both are optional, so you are able to add a callback for the success or failure case only.

Resources:

Guide to JavaScript PromisePromise API Reference


Update (2017/06/11)

The purpose of async/await function is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just like Promises are similar to structured callbacks, async/await is similar to combining generators and promises. -MDN

Also read Why Async/Await is better than Promise

Comment and share

Author's picture

Zhao Cai

What will your verse be?


Web developer


Toronto