- Node.js Web Development
- David Herron
- 386字
- 2021-06-25 21:54:02
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.
- Learning Apex Programming
- 深入淺出Java虛擬機:JVM原理與實戰
- Python應用輕松入門
- Hands-On RESTful Web Services with Go
- 深度學習:算法入門與Keras編程實踐
- SQL基礎教程(第2版)
- ExtJS高級程序設計
- Java面向對象程序設計
- Mastering Linux Security and Hardening
- Visual Studio Code 權威指南
- Building Serverless Architectures
- UX Design for Mobile
- Flask開發Web搜索引擎入門與實戰
- Opa Application Development
- Java Web開發任務教程