Converting Synchronous Code to Asynchronous
Tags: javascript, tutorial, async
Published: 2019-12-19 19:33:08

---
title: Converting Synchronous Code to Asynchronous
published: true
date: 2019-11-08 00:00:00 UTC
tags: javascript, tutorial, async
canonical_url: https://stephencharlesweiss.com//2019-11-18/convert-synchronous-to-asynchronous-code-javascript/
---

I often find myself looking up patterns for converting synchronous code into async variants in Javascript. Whether it’s remembering how exactly Promise chains work or what I need to do to create a Promise - there always seems to be one part that trips me up.

I wanted to document a simple, but I think representative, example of how to take a synchronous function and convert it to be asynchronous in Javascript.

I’ll be using a node function that is reading a file from the file system.

The original function is:

```javascript
const findAssetSync = (name) => {
  const assetPath = path.join(__dirname, 'assets', name)
  return fs.readFileSync(assetPath, {encoding: 'utf-8'}).toString()
}
```

The first step is to make this function return a promise instead.

```javascript
const findAssetAsync = (name) => {
    const assetPath = path.join(__dirname, 'assets', name)
    return new Promise((resolve, reject) => {
        fs.readFile(assetPath, {encoding: 'utf-8'}, (err, data) => {
            if (err) reject(err);
            return resolve(data);
          })
      })
}
```

Now, let’s look at how this would actually be used. I’ll start with the synchronous version.<sup>[1](#footnotes)</sup><a id="fn1"></a>

```javascript
const server = http.createServer((req, res) => {
  const route = url.parse(req.url).pathname
  if (routes[route]) {
    const assets = findAssetSync(routes[route])
    res.write(assets)
    res.end()
  } else {
    res.writeHead(404, ‘Not Found’)
    res.end()
  }
})
```

To use the asynchronous version, however, we either need to convert the callback within `createServer` into an `Async/Await` function or now use a promise chain.

The point, however, is that now, instead of returning the string itself as we do in `findAssetSync`, `findAssetAsync` returns a promise.

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Using Promise Chain

Promise chains create some complexity. Because we want to to make sure we resolve _before_ moving onto the writing of the server response - we can’t do this:

```javascript
const server = http.createServer(req, res) => {
  /* ... */
  if (routes[route]) {
    let assets = findAssetAsync(routes[route]).then(results => {
      assets = results;
    }).catch(err => console.error(err))
    res.write(assets)
    res.end()
  } else {
    /* ... */
  }
})
```

This would error, because while the promise is resolving, node would just continue moving along and reading the file — so we’d write assets (which would be undefined at the time) and then end the response.

To handle this - we place the response _inside_ the `.then` block:

```javascript
const server = http.createServer(req, res) => {
  /* ... */
  if (routes[route]) {
    findAssetAsync(routes[route]).then(results => {
      res.write(results)
      res.end()
    }).catch(err => console.error(err))
  } else {
    /* ... */
  }
})
```

It’s easy to see how, if this were to get much more complicated - and/or you wanted to carry variables forward (instead of just using the “response” variable from a Promise) how this can quickly get messy.<sup>[2](#footnotes)</sup><a id="fn2"></a>

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Using Async/Await

The async await syntax is much simpler to reason through. While it’s _not_ creating synchronous code - it reads as if it is. And underneath, it’s all just using Promises.

```javascript
const server = http.createServer( async (req, res) => {
  /* ... */
  if (routes[route]) {
    const assets = await findAssetAsync(routes[route])
    res.write(assets)
    /* ... */
  } else {
    /* ... */
  }
})
```

That’s it. We’re now waiting for the Async function to resolve _before_ preceeding - all while not blocking other requests.

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Conclusion

Converting from synchronous to asynchronous javascript code is not particularly difficult. It’s a matter of understanding _what_ is actually happening with the event loop and then pattern recognition.

## <svg aria-hidden="true" focusable="false" height="16" version="1.1" viewbox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>Footnotes

- <sup>[1](#fn1)</sup> I have simplified the code here a bit. For example, we’re missing the `routes` object that I’m looking for the `route`. 
- <sup>[2](#fn2)</sup> I found Danny Moerkeke’s article on [Async Programming in JavaScript](https://medium.com/swlh/what-you-need-to-know-about-asynchronous-programming-in-javascript-894f90a97941) particularly helpful in highlighting this challenge.