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});
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
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"
1let myPromise = new Promise(function(myResolve, myReject) {
2// "Producing Code" (May take some time)
3
4 myResolve(); // when successful
5 myReject(); // when error
6});
7
8// "Consuming Code" (Must wait for a fulfilled Promise)
9myPromise.then(
10 function(value) { /* code if successful */ },
11 function(error) { /* code if some error */ }
12);