Open cheungseol opened 6 years ago
util.promisify 是 NodeJS version8+版本的新功能,它接受一个函数作为参数,并将函数转换为promise函数。最为结果返回的promise函数自持promise语法(链式)和 async/await 语法。
注意
作为util.promisify参数的函数,需要满足 NodeJS callback 规范:
promise
const {promisify} = require('util'); const fs = require('fs'); const readFileAsync = promisify(fs.readFile); // (A) const filePath = process.argv[2]; readFileAsync(filePath, {encoding: 'utf8'}) .then((text) => { console.log('CONTENT:', text); }) .catch((err) => { console.log('ERROR:', err); });
async/await
const {promisify} = require('util'); const fs = require('fs'); const readFileAsync = promisify(fs.readFile); const filePath = process.argv[2]; async function main() { try { const text = await readFileAsync(filePath, {encoding: 'utf8'}); console.log('CONTENT:', text); } catch (err) { console.log('ERROR:', err); } } main();
async自执行函数
const util = require('util'); const fs = require('fs'); const stat = util.promisify(fs.stat); (async () => { let stats; try { stats = await stat('.'); } catch (err) { return console.error(err); } return console.log(stats); })();
Node8’s util.promisify is so freakin’ awesome!
Node.js 8: util.promisify()
util.promisify 是 NodeJS version8+版本的新功能,它接受一个函数作为参数,并将函数转换为promise函数。最为结果返回的promise函数自持promise语法(链式)和 async/await 语法。
注意
作为util.promisify参数的函数,需要满足 NodeJS callback 规范:
示例:
promise
async/await
async自执行函数
参考
Node8’s util.promisify is so freakin’ awesome!
Node.js 8: util.promisify()