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});
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);
1//Promise to load a file...
2//use with openFile(url, fCallback);
3//fCallback(fileContents){ //do something with fileContents}
4const loadFile = url => {
5 return new Promise(function(resolve, reject) {
6 //Open a new XHR
7 var request = new XMLHttpRequest();
8 request.open('GET', url);
9 // When the request loads, check whether it was successful
10 request.onload = function() {
11 if (request.status === 200) {
12 // If successful, resolve the promise
13 resolve(request.response);
14 } else {
15 // Otherwise, reject the promise
16 reject(Error('An error occurred while loading image. error code:' + request.statusText));
17 }
18 };
19 request.send();
20 });
21};
22const openFile = (url, processor) => {
23 loadFile(url).then(function(result) {
24 processor(result);
25 },
26 function(err) {
27 console.log(err);
28 });
29};
1A promise is an object that may produce a single value some time in the future:
2either a resolved value, or a reason that it’s not resolved
1// Promise is a special type of object that helps you work with asynchronous operations.
2// Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
3
4const userCount = getUserCount();
5console.log(userCount); // Promise {<pending>}
6
7// In this case, getUserCount is the function that returns a Promise. If we try to immediately display the value of the userCount variable, we get something like Promise {<pending>}.
8// This will happen because there is no data yet and we need to wait for it.
1Promises make async javascript easier as they are easy to use and write than callbacks. Basically , promise is just an object , that gives us either success of async opertion or failue of async operations