Promises in Node.js core

筅森魡賤 提交于 2019-12-19 11:42:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!