Skip to content

Instantly share code, notes, and snippets.

@Terance98
Created March 5, 2020 16:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Terance98/5fec0b02f3ffb84bf2f90f3be8f67d10 to your computer and use it in GitHub Desktop.
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.
//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);
@Terance98
Copy link
Author

Initial commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment