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
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"
1/*
2Promise is a constructor function, so you need to use the new keyword to
3create one. It takes a function, as its argument, with two parameters -
4resolve and reject. These are methods used to determine the outcome of the
5promise.
6The syntax looks like this:
7*/
8
9const myPromise = new Promise((resolve, reject) => {
10
11});
12
13
1const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
2 resolutionFunc(777);
3});
4// At this point, "promiseA" is already settled.
5promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
6console.log("immediate logging");
7
8// produces output in this order:
9// immediate logging
10// asynchronous logging has val: 777
11