try/catch blocks with async/await

I’m digging into the node 7 async/await feature and keep stumbling across code like this function getQuote() { let quote = “Lorem ipsum dolor sit amet, consectetur adipiscing elit laborum.”; return quote; } async function main() { try { var quote = await getQuote(); console.log(quote); } catch (error) { console.error(error); } } main(); This seems … Read more

Use async await with Array.map

Given the following code: var arr = [1,2,3,4,5]; var results: number[] = await arr.map(async (item): Promise<number> => { await callAsynchronousOperation(item); return item + 1; }); which produces the following error: TS2322: Type ‘Promise<number>[]’ is not assignable to type ‘number[]’. Type ‘Promise<number> is not assignable to type ‘number’. How can I fix it? How can I … Read more

How can I use async/await at the top level?

I have been going over async/await and after going over several articles, I decided to test things myself. However, I can’t seem to wrap my head around why this does not work: async function main() { var value = await Promise.resolve(‘Hey there’); console.log(‘inside: ‘ + value); return value; } var text = main(); console.log(‘outside: ‘ … Read more

How to reject in async/await syntax?

How can I reject a promise that returned by an async/await function? e.g. Originally: foo(id: string): Promise<A> { return new Promise((resolve, reject) => { someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400)) }); } Translate into async/await: async foo(id: string): Promise<A> { try{ await someAsyncPromise(); return 200; } catch(error) {//here goes if someAsyncPromise() rejected} return 400; //this will result in a resolved … Read more

Combination of async function + await + setTimeout

I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working: async function asyncGenerator() { // other code while (goOn) { // other code var fileList = await listFiles(nextPageToken); var parents = await requestParents(fileList); // other code } … Read more

Using async/await with a forEach loop

Are there any issues with using async/await in a forEach loop? I’m trying to loop through an array of files and await on the contents of each file. import fs from ‘fs-promise’ async function printFiles () { const files = await getFilePaths() // Assume this works fine files.forEach(async (file) => { const contents = await … Read more