JavaScript Async and Await

I scratched my head for a while when switching from promises to await/async. Hopefully this post helps you not need to scratch yours! 😀

Async/await is the same as using promises. It’s just syntactical sugar to make it look synchronous. The javascript engine sees the “await” and stops execution there for you automatically until the promise is resolved/rejected.

I find the javascript promise with ‘.then()’ and ‘.catch()’ is much nicer if you have really simple things to do with the result and the error. But, as soon as you start getting into a bunch of conditionals, from your results, you tend to get a lot of nested promise call statements. So, to save you from promise hell, you just label your function as async, and use the await expression so that you don’t have to be too concerned with promise management. Then hopefully what you do with the final result is simple, and you then resort to using promises. See the testPromise() calls below for examples.

/**
* @param fail if true, throw an error with a promise. If false, resolve
* a delayed response with a promise.
* @returns {Promise<*>} Always a promise resolve or reject.
*/

function testPromise(fail) {
if (fail) {
return Promise.reject(new Error('failed'));
}
else {
return new Promise(resolve => setTimeout(function () {
resolve('success')
}, 1000));
}
}

/**
* Test calls with promises, awaits, and async.
*
* @param fail if true, fail with error. If false, succeed normally.
* @returns {Promise<*>} always a promise, as async/await use promises as
* does Promise.reject and Promise.resolve.
*/

async function testAsync(fail) {
let result = await testPromise(fail);
return result;
}

testAsync(true)
.then(v => console.log('fail: ', v))
.catch(e => console.log('fail: ', e.message));
testPromise(true)
.then(v => console.log('fail w/promise: ', v))
.catch(e => console.log('fail w/promise: ', e.message));

testAsync(false)
.then(v => console.log('succeed: ', v))
.catch(e => console.log('succeed: ', e.message));
testPromise(false)
.then(v => console.log('succeed w/promise: ', v))
.catch(e => console.log('succeed w/promise: ', e.message));

/**
* This shows that within an async function you can try/catch instead of
* then/catch, as long as you use "await".
*
* @returns {Promise<void>}
*/

async function testWithTry() {
try {
let result = await testPromise(true);
console.log('fail w/try: ', result);
} catch (e) {
console.log('fail w/try: ', e.message)
}
try {
let result = await testPromise(true);
console.log('fail w/try w/promise: ', result);
} catch (e) {
console.log('fail w/try w/promise: ', e.message)
}

try {
let result = await testPromise(false);
console.log('succeed w/try: ', result);
} catch (e) {
console.log('succeed w/try: ', e.message)
}
try {
let result = await testPromise(false);
console.log('succeed w/try w/promise: ', result);
} catch (e) {
console.log('succeed w/try w/promise: ', e.message)
}
}

testWithTry();