Skip to content

Instantly share code, notes, and snippets.

@E3V3A
Forked from alexkrolick/async-test.js
Created February 28, 2018 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save E3V3A/14e6851e8d2f42e74a1d75546c6b4628 to your computer and use it in GitHub Desktop.
Save E3V3A/14e6851e8d2f42e74a1d75546c6b4628 to your computer and use it in GitHub Desktop.
Async-Await vs Promises in Node
// Before April 2017 run this with flags:
// node --harmony-async-await ./async-test.js
function sayHi (name) {
if (name == null) throw Error('Missing name')
return `Hi ${name}.`
}
function sayWhatsUpAsync (msg, timeoutMs) {
console.log(`Will return in ${timeoutMs / 1000}s`)
return new Promise((resolve, reject) => {
setTimeout(() => {
if (msg == null) reject(Error('Empty message'))
resolve(`${msg} What is up?`)
}, timeoutMs)
})
}
async function errorfree () {
console.log('\nRunning function without errors...')
try {
let greeting = sayHi('Alejandro')
greeting = await sayWhatsUpAsync(greeting, 2000)
console.log(greeting)
} catch (err) {
console.error(err)
}
}
async function errorfulSync () {
console.log('\nRunning function with sync errors...')
try {
let greeting = sayHi() // errors on empty input
greeting = await sayWhatsUpAsync(greeting, 2000)
console.log(greeting)
} catch (err) {
console.error(err)
}
}
async function errorfulAsync () {
console.log('\nRunning function with async errors...')
try {
let greeting = null; // next call checks for null input and errors
greeting = await sayWhatsUpAsync(greeting, 2000)
console.log(greeting)
} catch (err) {
console.error(err)
}
}
async function mainAsync () {
await errorfree() // delay next call until this one finishes
await errorfulSync() // delay next call until this one finishes
errorfulAsync()
}
mainAsync()
// Run with:
// node promist-test.js
function sayHiAsync (name) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
resolve(`Hi, ${name}`)
}, 2000)
})
}
function sayWhatsUpAsync (msg) {
if (msg == null) throw Error('Missing message sync')
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (msg === 'Hi, JZ') reject(Error('Do not speak to JZ'))
resolve(`${msg} What is up?`)
}, 2000)
})
}
function beExcited (msg) {
if (msg == null) throw Error('Missing message')
return msg + '!'
}
sayHiAsync('Lily')
.then(function (msg) {
return msg + '1' // ES5 anonymous function style
})
.then((msg) => {
return msg + '2' // ES6 anonymous function
})
.then(msg => msg + '3') // ES6 shortcut anonymous function
.then(sayWhatsUpAsync) // Pass function handle directly
.then(beExcited)
.then(console.log) // Log final value
.catch(err => console.error('We caught an error: ', err)) // catch error
// Intermediate sync call throws
sayHiAsync('JZ')
.then(msg => null) // intermediate function returns null
.then(beExcited) // this function handles null input as error
.then(console.log) // this gets skipped
.catch(err => console.error('We caught an error: ', err)) // catch error
// Intermediate async call throws
sayHiAsync('JZ')
.then(sayWhatsUpAsync) // throws async error
.then(beExcited) // this function is skipped
.then(console.log) // this is skipped
.catch(err => console.error('We caught an error: ', err)) // catch error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment