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});
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};
1getData()
2 .then(data => console.log(data))
3 .catch(error => console.log(error));
1firstRequest()
2 .then(function(response) {
3 return secondRequest(response);
4}).then(function(nextResponse) {
5 return thirdRequest(nextResponse);
6}).then(function(finalResponse) {
7 console.log('Final response: ' + finalResponse);
8}).catch(failureCallback);