how to use promise in javascript code example
Example 1: js create a promise
/*
A Promise is a proxy for a value not necessarily known when the promise is created.
It allows you to associate handlers with an asynchronous action's eventual success
value or failure reason.
*/
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
// successfully got data
resolve(res);
})
.catch((err) => {
// an error occured
reject(err);
});
});
Example 2: javascript promise
var promise = new Promise(function(resolve, reject) {
// do some long running async thing…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
//usage
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
Example 3: js promise examples
//Promise to load a file...
//use with openFile(url, fCallback);
//fCallback(fileContents){ //do something with fileContents}
const loadFile = url => {
return new Promise(function(resolve, reject) {
//Open a new XHR
var request = new XMLHttpRequest();
request.open('GET', url);
// When the request loads, check whether it was successful
request.onload = function() {
if (request.status === 200) {
// If successful, resolve the promise
resolve(request.response);
} else {
// Otherwise, reject the promise
reject(Error('An error occurred while loading image. error code:' + request.statusText));
}
};
request.send();
});
};
const openFile = (url, processor) => {
loadFile(url).then(function(result) {
processor(result);
},
function(err) {
console.log(err);
});
};
Example 4: what is a promise
// Promise is a special type of object that helps you work with asynchronous operations.
// Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
const userCount = getUserCount();
console.log(userCount); // Promise {<pending>}
// 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>}.
// This will happen because there is no data yet and we need to wait for it.
Example 5: .promise()
var promise = new Promise(function(resolve, reject) {
// do some long running async thing…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Example 6: promise javascript
const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777