Skip to content

sgilroy/async-await-codemod

Repository files navigation

async-await-codemod

Build Status Code Style: prettier

This repository contains a codemod script for use with JSCodeshift that migrates promise-based functions to use async/await syntax.

The excellent sinon-codemod repository was used as inspiration and served as a template for this repository.

This codemod is based in part on work done by @cpojer https://github.com/cpojer/js-codemod/pull/49/commits/19ed546d8a47127d3d115f933d924106c98e1b8b and the further work of @cassilup https://github.com/cassilup/async-await-codemod-demo

Setup & Run

  • npm install -g jscodeshift
  • git clone https://github.com/sgilroy/async-await-codemod.git or download a zip file from https://github.com/sgilroy/async-await-codemod/archive/master.zip
  • Run npm install in the async-await-codemod directory
    • Alternatively, run yarn to install in the async-await-codemod directory
  • jscodeshift -t <codemod-script> <path>
  • Use the -d option for a dry-run and use -p to print the output for comparison

async-await

ES2017 natively supports a special syntax for working with promises called "async/await".

With promises:

function makeRequest() {
  return getJSON().then(data => {
    console.log(data);
    return 'done';
  });
}

With async/await:

async function makeRequestFunction() {
  const data = await getJSON();
  console.log(data);
  return 'done';
}

Included Scripts

async-await

Converts each asynchronous function (a function which contains a .then() call) to async, and uses await instead of .then() to simplify the behavior of using promises synchronously.

jscodeshift -t async-await-codemod/async-await.js <path>

await-promise-chain

Unravels chained promise calls of the style foo.then().then() as multiple await calls. Note that this changes the structure and scope of blocks of code and can thus result in different behavior, such as by variables being in scope that otherwise would not.

This should generally be used after the async-await codemod, and the changes should be examined and tested carefully to avoid unwanted bugs or subtle problems.

jscodeshift -t async-await-codemod/await-promise-chain.js <path>

About

Codemod script for migrating promise-based functions to use async/await syntax

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published