function doSomething() {
return new Promise((resolve, reject) => {
console.log("It is done.");
// Succeed half of the time.
if (Math.random() > .5) {
resolve("SUCCESS")
} else {
reject("FAILURE")
}
})
}
const promise = doSomething();
promise.then(successCallback, failureCallback);
const address = fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => {
return user.address;
});
const printAddress = async () => {
const a = await address;
console.log(a);
};
printAddress();
module.exports.getAllPosts = function()
{
return new Promise((resolve,reject)=>{
if(posts == true)
{
resolve("success");
}else{
reject("Failed");
}
});
}
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);
}
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));