1new Promise( (res, rej) => {
2 setTimeout(() => res(1), 1000);
3}).then( (res) => {
4 console.log(res); // 1
5 return res*2
6}).then( (res) => {
7 console.log(res); // 2
8});
9
1var promise = new Promise(function(resolve, reject) {
2 // do some long running async thing…
3
4 if (/* everything turned out fine */) {
5 resolve("Stuff worked!");
6 }
7 else {
8 reject(Error("It broke"));
9 }
10});
11
12//usage
13promise.then(
14 function(result) { /* handle a successful result */ },
15 function(error) { /* handle an error */ }
16);
1A promise is an object that may produce a single value some time in the future:
2either a resolved value, or a reason that it’s not resolved
1// Promise is a special type of object that helps you work with asynchronous operations.
2// Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
3
4const userCount = getUserCount();
5console.log(userCount); // Promise {<pending>}
6
7// In this case, getUserCount is the function that returns a Promise. If we try to immediately display the value of the userCount variable, we get something like Promise {<pending>}.
8// This will happen because there is no data yet and we need to wait for it.
1import isPromise from 'is-promise';
2
3isPromise(Promise.resolve());//=>true
4isPromise({then:function () {...}});//=>true
5isPromise(null);//=>false
6isPromise({});//=>false
7isPromise({then: true})//=>false
1let promise = new Promise(function(resolve, reject){
2 try{
3 resolve("works"); //if works
4 } catch(err){
5 reject(err); //doesn't work
6 }
7}).then(alert, console.log); // if doesn't work, then console.log it, if it does, then alert "works"