const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
myPromise
.then(handleResolvedA, handleRejectedA)
.then(handleResolvedB, handleRejectedB)
.then(handleResolvedC, handleRejectedC);
function justTesting(input) {
return new Promise(function(resolve, reject) {
// some async operation here
setTimeout(function() {
// resolve the promise with some value
resolve(input + 10);
}, 500);
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}
async function abc()
{
Promise.resolve("hello world").then(function(value)
{
console.log(value);
}
let fetchSent = fetch("/test", {method:"POST", body: JSON.stringify({name:"NAME NAME NAME"}), headers: {'Content-type': 'application/json; charset=UTF-8'}});
const p1 = new Promise((resolve, reject) => {
resolve(fetchSent);
// or
// reject(new Error("Error!"));
})
return p1;
/*console.log(p1) will yield the fetch promise that was sent to you*/
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();
});
}
// ? created a function that returns a promise, take a parameter of a boolean
function myPromise(bool) {
return new Promise((resolve, reject) => {
if (bool) {
resolve("I have succeeded");
} else {
reject("I have failed");
}
});
}
// ? call the function and pass in a boolean
myPromise(true).then((res) => console.log(res));
myPromise(false).then((res) => console.log(res)).catch((err) => console.log(err));