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 thepromises
object of thefs
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:
We import the promises object of the
fs
module to get access to all thefs
functions already promisified.We manually promisify the
mkdirp()
function. ... ...