I hear that Promises are available for Node core APIs. For example with fs, how can we use promises, do we just omit the callback?
fs.readFile(file).then(v => console.log(v));
or how do we use?
at the moment for Node.js versions older than 10, I am guessing, it's behind a flag? Maybe: node --promises
?
As of now, most Node callback-based APIs should be manually promisified in order to make use of promises.
util.promisify
is available since Node 8 (also polyfillable ) and allows to promisify any APIs that use error-first callbacks, including built-in fs
:
const { promisify } = require('util');
const fs = require('fs');
const readFile = promisify(fs.readFile);
readFile(file).then(console.log);
Some APIs that use non-error-first callbacks support it too via util.promisify.custom
symbol, eg setTimeout
:
promisify(setTimeout)(100).then(...);
fs.promises
experimental API is available since Node 10 ( polyfillable in Node 8 and higher) and contains promisified fs
module, as already mentioned in another question:
const fsp = require('fs').promises;
fsp.readFile(file).then(console.log);
For batch promisification third-party tools like pify
can be used.
Third-party promisification packages are available for most built-in and popular third-party callback-based packages that can be converted to promises, eg fs-extra
, which is a preferable drop-in replacement for fs
that includes essential graceful-fs
package.
This experimental feature was added in node v10.0.0. You'll need to require fs/promises
instead of fs
使用可以使用mz :
var fs = require('mz/fs');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.