Last active
July 3, 2018 18:16
-
-
Save pmuellr/87fbc22b7217f68c4a8abd7d192c70d4 to your computer and use it in GitHub Desktop.
see what async functions return when returning early, and after an await
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
'use strict' | |
async function delay (ms) { | |
return new Promise((resolve, reject) => setTimeout(resolve, ms)) | |
} | |
async function foo (returnEarly) { | |
if (returnEarly) return new Date() | |
await delay(1000) | |
return new Date() | |
} | |
const TRACE = process.env.TRACE != null | |
async function main () { | |
if (TRACE) console.trace(1); console.log('foo(true): ', foo(true)) | |
if (TRACE) console.trace(2); console.log('await foo(true): ', await foo(true)) | |
if (TRACE) console.trace(3); console.log('foo(false): ', foo(false)) | |
if (TRACE) console.trace(4); console.log('await foo(false):', await foo(false)) | |
if (TRACE) console.trace(5) | |
// prints: | |
// foo(true): Promise { 2018-07-03T18:14:54.014Z } | |
// await foo(true): 2018-07-03T18:14:54.017Z | |
// foo(false): Promise { <pending> } | |
// await foo(false): 2018-07-03T18:14:55.021Z | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment