问题
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
?
回答1:
This experimental feature was added in node v10.0.0. You'll need to require fs/promises
instead of fs
回答2:
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, e.g. 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, e.g. fs-extra, which is a preferable drop-in replacement for fs
that includes essential graceful-fs
package.
回答3:
Use can use mz :
var fs = require('mz/fs');
来源:https://stackoverflow.com/questions/51111181/promises-in-node-js-core