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);
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//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
1const executorFunction = (resolve, reject) => {
2 if (someCondition) {
3 resolve('I resolved!');
4 } else {
5 reject('I rejected!');
6 }
7}
8const myFirstPromise = new Promise(executorFunction);
1const prom = new Promise((resolve, reject) => {
2 resolve('Yay!');
3});
4
5const handleSuccess = (resolvedValue) => {
6 console.log(resolvedValue);
7};
8
9prom.then(handleSuccess); // Prints: 'Yay!'