...

/

Sequential Execution and Iteration

Sequential Execution and Iteration

Learn to implement sequential asynchronous operations with promises.

We'll cover the following...

Sequential execution

Now that we’re familiar with web spider applications, we’ll create one that uses promises. Let’s start with the web spider example that downloads the links of a web page in sequence.

Note: We can access an already promisified version of the core fs API through the promises object of the fs module. For example: import { promises } from 'fs'.

In the spider.js module, the very first step required is to import our dependencies and promisify any callback-based function that we’re going to use:

import { promises as fsPromises } from 'fs' //(1)
import { dirname } from 'path'
import superagent from 'superagent'
import mkdirp from 'mkdirp'
import { urlToFilename, getPageLinks } from './utils.js'
import { promisify } from 'util'
const mkdirpPromises = promisify(mkdirp) //(2)

There are two main differences here compared to the spider.js module of the previous chapter:

  1. We import the promises object of the fs module to get access to all the fs functions already promisified.

  2. We manually promisify the mkdirp() function. ... ...