const returnPromiseFunction = () => { return new Promise((resolve, reject) => { setTimeout(( ) => {resolve('I resolved!')}, 1000); }); }; code example
Example 1: js create a promise
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
});
Example 2: js promise examples
const loadFile = url => {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function() {
if (request.status === 200) {
resolve(request.response);
} else {
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);
});
};