resolve and reject in promise 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);
});
};
Example 3: promise resolve reject
function testFunction(value) {
return new Promise(function (resoleve, reject) {
setTimeout(function () {
let n = value;
if (n < 100) {
resoleve("範囲内");
} else {
reject("範囲外");
}
}, 2000);
})
}
testFunction(10)
.then(function (value) {
console.log(value);
return testFunction(50);
})
.then(function (value) {
console.log(value);
return testFunction(150);
})
.catch(function (error) {
console.log(`エラーです。${error}`);
})
Example 4: promise resolve reject
function testFunction() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('hello!');
}, 1000);
})
}
testFunction()
.then(function (value) {
console.log(value);
})
.catch(function (error) {
console.log(error);
})
Example 5: promise resolve reject
function testFunction(value) {
return new Promise(function (resoleve, reject) {
setTimeout(function () {
let n = value;
if(n<100){
resoleve("範囲内");
}else{
reject("範囲外");
}
}, 2000);
})
}
testFunction(1000)
.then(function (value) {
console.log(value);
})
.catch(function(error){
console.log(`エラーです。${error}`);
})