Created
March 5, 2020 16:02
-
-
Save Terance98/5fec0b02f3ffb84bf2f90f3be8f67d10 to your computer and use it in GitHub Desktop.
This gist contains a sample snippet of javascript code that explains pretty well the use of Javascript promises, how to unpack them with then() etc.. This also uses prototype chaining with multiple then() clauses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Here the first Promise resolves and then returns Done to the function inside first then(), | |
//but this function doesn't take any parameters and hence the value "Done" is never used. | |
// But the value is still being returned from the Promise to the function where it is unpacked. | |
// The fetchData promise is returned again by the function inside the first then() that unpacked the promise initially. | |
// This promise then gets resolved with console.log as the input parameter function, which takes one parameter as input and prints it. | |
// So it should take total 3 seconds to print Done!. This promise makes use of the returned Done value by printing it to the console with console.log() | |
const fetchData = () => { | |
const promise = new Promise((resolve, reject) => { | |
setTimeout(() => resolve('Done'), 1500); | |
}); | |
return promise; | |
} | |
setTimeout(() => { | |
console.log("Hello this is inside the timer & it is done!"); | |
fetchData() | |
.then(() => { | |
console.log("1.5 seconds over!") | |
return fetchData(); | |
}) | |
.then(console.log); | |
}, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Initial commit.