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});
1//create a Promise
2var p1 = new Promise(function(resolve, reject) {
3 resolve("Success");
4});
5
6//Execute the body of the promise which call resolve
7//So it execute then, inside then there's a throw
8//that get capture by catch
9p1.then(function(value) {
10 console.log(value); // "Success!"
11 throw "oh, no!";
12}).catch(function(e) {
13 console.log(e); // "oh, no!"
14});
15
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);
1const myPromise = new Promise((resolve, reject) => {
2 setTimeout(() => {
3 resolve('foo');
4 }, 300);
5});
6
7myPromise
8 .then(handleResolvedA, handleRejectedA)
9 .then(handleResolvedB, handleRejectedB)
10 .then(handleResolvedC, handleRejectedC);
11
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});
1myPromise.then(
2 function(value) { /* code if successful */ },
3 function(error) { /* code if some error */ }
4);