js new 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: javascript promise
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(
function(result) { },
function(error) { }
);
Example 3: javascript create promise
const promise = new Promise(executor);
const coinflip = (bet) => new Promise((resolve, reject) => {
const hasWon = Math.random() > 0.5 ? true : false;
if (hasWon) {
setTimeout(() => {
resolve(bet * 2);
}, 2000);
} else {
reject(new Error("You lost..."));
}
});
Example 4: 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 5: js return a promise
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
Example 6: .promise()
var promise = new Promise(function(resolve, reject) {
if () {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});