async/await syntax indiosyncrasy1

// With function declaration
async function myFn() {
  // await ...
}
// With arrow function
const myFn = async () => {
  // await ...
}
function myFn() {
  // await fn(); (Syntax Error since no async)
}
// As an object's method
const obj = {
  async getName() {
    return fetch('https://www.example.com');
  }
}
// In a class
class Obj {
  async getResource() {
    return fetch('https://www.example.com');
  }
}
// Note: Class constructors and getters/setters cannot be async.

An async function always returns a promise.

async function fn() {
  return 'hello';
}
fn().then(console.log)
// hello

Here’s an alternate representation without using async —

function fn() {
  return Promise.resolve('hello');
}
fn().then(console.log);
// hello

async map

async function fetchAllCounts(users) {
  const promises = users.map(async username => {
    const count = await fetchPublicReposCount(username);
    return count;
  });
  return Promise.all(promises);
}

useful object functions

map over an object


// returns a new object with the values at each key mapped using
export const objectMap = (obj: any, mapFn: Function): Object => Object
  .keys(obj)
  .reduce((result: any, key: any) => {
    result[key] = mapFn(obj, key, obj[key]);
    return result;
  }, {});

object equality using string comparison

export const equalObject = (obj1: Object, obj2: Object): Boolean => JSON.stringify(obj1) === JSON.stringify(obj2)

check if object is empty

export const isEmptyObject = (obj: Object): Boolean => Object.entries(obj).length === 0 && obj.constructor === Object

useful array functions

flatten array

export const flattenArray = (items: Array<any>): Array<any> => [].concat.apply([], items)

check if something is undefined

const isUndefined = (x: any): Boolean => x === undefined

Footnotes

https://blog.bitsrc.io/understanding-javascript-async-and-await-with-examples-a010b03926ea