1/*
2 A Promise is a proxy for a value not necessarily known when the promise is created.
3 It allows you to associate handlers with an asynchronous action's eventual success
4 value or failure reason.
5*/
6let promise = new Promise((resolve , reject) => {
7 fetch("https://myAPI")
8 .then((res) => {
9 // successfully got data
10 resolve(res);
11 })
12 .catch((err) => {
13 // an error occured
14 reject(err);
15 });
16});
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
1// base case
2const promise = new Promise(executor);
3
4// more complex example
5const coinflip = (bet) => new Promise((resolve, reject) => {
6 const hasWon = Math.random() > 0.5 ? true : false;
7 if (hasWon) {
8 setTimeout(() => {
9 resolve(bet * 2);
10 }, 2000);
11 } else {
12 reject(new Error("You lost...")); // same as -> throw new Error ("You lost ...");
13 }
14});
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);
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"
1myPromise
2.then(handleResolvedA)
3.then(handleResolvedB)
4.then(handleResolvedC)
5.catch(handleRejectedAny)
6.finally(handleComplition)
7