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});
1function doSomething() {
2 return new Promise((resolve, reject) => {
3 console.log("It is done.");
4 // Succeed half of the time.
5 if (Math.random() > .5) {
6 resolve("SUCCESS")
7 } else {
8 reject("FAILURE")
9 }
10 })
11}
12
13const promise = doSomething();
14promise.then(successCallback, failureCallback);
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
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);
1const someThing = new Promise((resolve, reject) => {
2 //Example Axios is used
3 axios
4 .get("/get-some-data-some-some-where")
5 .then(function({ data }) {
6 resolve(data);
7 })
8 .catch(error => {
9 reject(error);
10 });
11 });
12
13const someThingTwo = new Promise((resolve, reject) => {
14 //Example Axios is used
15 axios
16 .get("/get-some-data-from-somewhere-else")
17 .then(function({ data }) {
18 resolve(data);
19 })
20 .catch(error => {
21 reject(error);
22 });
23 });
24
25
26Promise.all([someThing, someThingTwo]).then(
27 res => {
28 const SomeVariable = res[0]; //Data from someThing
29 const SomeVariable2 = res[1]; //Data from someThingTwo
30
31 },
32 error => {
33 console.log(error)
34 }
35 );