let myFirstPromise = new Promise((resolve, reject) => {
// We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
// In this example, we use setTimeout(...) to simulate async code.
// In reality, you will probably be using something like XHR or an HTML5 API.
setTimeout(function(){
resolve("Success!"); // Yay! Everything went well!
}, 2500);
});
myFirstPromise.then((successMessage) => {
// successMessage is whatever we passed in the resolve(...) function above.
// It doesn't have to be a string, but if it is only a succeed message, it probably will be.
element = document.querySelector(".world");
element.innerHTML =("Yay! " + successMessage);
});
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
// https://developers.google.com/web/fundamentals/primers/promises#whats-all-the-fuss-about
// chained promise example
function cleanRoom(){
return new Promise(function (resolve,reject){
resolve('Cleaned the room');
})
}
function removeGarbage(promise) {
return new Promise(function(resolve,reject){
resolve('remove the garbage');
})
}
function winIcecream(promise) {
return new Promise(function(resolve,reject){
resolve('won IceCream');
})
}
// call the start of the chain
cleanRoom().then(() =>{
// return the next functions promise
return removeGarbage();
}).then(() =>{
// return the next function promise
return winIcecream();
// message to prove it worked.
}).then(() =>{
document.querySelector("#app").innerHTML = "finished the promise chain";
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.