Last active
October 8, 2020 00:12
-
-
Save thomastay/fd2a60aa9a8dcc7e29ad7c6629425332 to your computer and use it in GitHub Desktop.
Promise <-> Async await equivalence
This file contains hidden or 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" | |
// The following are equivalent (functionally) | |
// Async await | |
async function simple() { | |
await setTimeout(() => console.log("hello, world!"), 1000); | |
} | |
// Promises | |
function simple_promise() { | |
return Promise.resolve(() => setTimeout(() => console.log("hello, world!"), 1000)); | |
} | |
// Async await | |
async function await_at_end() { | |
let x = doSomethingAsync(); // x is a promise | |
x = x.then(() => console.log("hello, world!")); | |
await x; | |
} | |
// Promises | |
function await_at_end_promise() { | |
let x = doSomethingAsync(); // x is a promise | |
x = x.then(() => console.log("hello, world!")); | |
return x; | |
} | |
// Async await | |
async function try_catch() { | |
let result = -1; | |
try { | |
let x = await doSomethingAsync(); // x is a number | |
result = x+1; | |
} catch (err) { | |
console.log(err.message); | |
} | |
return result; | |
} | |
// Promises | |
function try_catch_promise() { | |
let result = -1; | |
return doSomethingAsync() | |
.then(x => result = x+1) | |
.catch(err => console.log(err.message)) | |
.then(() => result); | |
} | |
// Async await | |
async function nested_catch() { | |
try { | |
await doSomethingAsync(); | |
try { | |
await doThing2Async(); | |
console.log("done"); | |
} catch (err) { | |
console.err(`thing2 failed with message ${err.message}`); | |
} | |
} catch (err) { | |
console.err(`doSomething failed with message ${err.message}`); | |
} | |
} | |
// Promises | |
function nested_catch_promise() { | |
return doSomethingAsync() | |
.then(() => { | |
doThing2Async() | |
.then(() => console.log("done")) | |
.catch(err => console.err(`thing2 failed with message ${err.message}`)) | |
}) | |
.catch(err => console.err(`doSomething failed with message ${err.message}`)) | |
} | |
// Async await | |
async function not_assigning() { | |
let x = await 10; | |
new Promise((resolve) => resolve(setTimeout(() => console.log(x), 100))); | |
new Promise((resolve) => resolve(console.log(`Hello, ${x}`))); | |
console.log("world!"); | |
} | |
// Promises | |
function not_assigning_promise() { | |
let x = Promise.resolve(10); | |
x.then(n => setTimeout(() => console.log(n), 100)); | |
x.then(n => console.log(`Hello, ${n}, `)); | |
x = x.then(() => console.log("world!")); | |
return x; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment