promise function javascript code example
Example 1: 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 2: 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 3: .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 4: promise js
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
Example 5: what is promise in javascript
Promises 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
Example 6: making promises in js
getData()
.then(data => console.log(data))
.catch(error => console.log(error));