官术网_书友最值得收藏!

Conversion to async functions and the Promise paradigm

In the previous section we discussed the util.promisify and its ability to convert a callback-oriented function into one that returns a Promise. The latter play well within async functions and therefore it is preferable for functions to return a Promise.

To be more precise, util.promisify is to be given a function that uses the error-first-callback paradigm. The last argument of such functions is a callback function whose first argument is interpreted as an error indicator, hence the phrase error-first-callback. What util.promisify returns is another function that returns a Promise. 

The Promise serves the same purpose as the error-first-callback. If an error is indicated, the Promise resolves to the rejected status, while if success is indicated the Promise resolves to a success status. As we see in these examples, within an async function the Promise is handled very nicely.

The Node.js ecosystem has a large body of functions using the error-first-callback. The community has begun a conversion process where functions will return a Promise, and possibly also take an error-first-callback for API compatibility.

One of the new features in Node.js 10 is an example of such a conversion. Within the fs module is a submodule, named fs.promises, with the same API but producing Promise objects. We could rewrite the previous example as so:

const fs = require('fs').promises;
(async () => {
var dir = '.';
if (process.argv[2]) dir = process.argv[2];
const files = await fs.readdir(dir);
for (let fn of files) {
console.log(fn);
}
})().catch(err => { console.error(err); });

As you can see, the functions in the fs.promises module returns a Promise without requiring a callback function. The new program, which you can save as ls2-promises.js, is run as so:

$ node ls2-promises.js 
(node:40329) ExperimentalWarning: The fs.promises API is experimental
app.js
ls.js
ls2-promises.js
ls2.js

The API is currently in an experimental state and therefore we're shown this warning.

Another choice is a 3rd party module, fs-extra. This module has an extended API beyond the standard fs module. On the one hand its functions return a Promise if no callback function is provided, or else invokes the callback. In addition it includes several useful functions.

In the rest of this book we will be using fs-extra because of those additional functions. For documentation of the module, see: https://www.npmjs.com/package/fs-extra.

主站蜘蛛池模板: 金秀| 周口市| 岫岩| 舒城县| 海南省| 东安县| 麻江县| 忻州市| 孟州市| 随州市| 惠安县| 钟祥市| 涪陵区| 海口市| 台前县| 曲沃县| 汶上县| 福安市| 宣威市| 青海省| 麟游县| 巧家县| 贞丰县| 沂水县| 扶余县| 北川| 汝城县| 闽清县| 宜宾县| 平谷区| 邯郸市| 兴隆县| 清新县| 鸡西市| 阳江市| 石阡县| 迭部县| 旬邑县| 丽江市| 元阳县| 正定县|