Last active
April 25, 2018 20:06
-
-
Save chandlerprall/88cc51c52fbd85f141930cb41feed1fc to your computer and use it in GitHub Desktop.
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
// myFunc will be executed asynchronously after the initial promise resolved | |
somePromise.then(myFunc) | |
// event if the originating promise doesn't do anything asynchronously | |
function quickPromise() { | |
// this function returns a promise that immediately resolves with "hello world" | |
return new Promise(resolve => { | |
resolve('hello world'); | |
}); | |
} | |
quickPromise().then(result => console.log(result)); // logs "hello world" | |
// to show that the console.log is still asynchronously executed we can console.log after firing the promise | |
quickPromise().then(result => console.log(result)); | |
console.log('this comes first'); | |
// logs "this comes first" follow by another log of "hello world" | |
// even though everything in the promise handling (quickPromise & the function in `then`) are themselves sychronous, | |
// a promise's resolving or rejecting is always added to the event loop after the current task | |
// how does this affect nested thens? | |
doSomething | |
.then(() => { // first outer promise | |
return somethingElse | |
.then(() => { // inner promise | |
doSync(); | |
}); | |
}) | |
.then(() => { // second outer promise | |
// keep going | |
}); | |
// first outer promise is scheduled on the event loop | |
// when it executes it puts inner promise on the event loop _and immediately returns_ which resolves its promise, scheduling second outer promise onto the event loop | |
// inner promise executes, which contains fully blocking synchronous code, node must wait for it to finish before advancing the loop | |
// second outer promise executes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment