cheungseol / cheungseol.github.io

2 stars 0 forks source link

[Node]-util.promisify #12

Open cheungseol opened 6 years ago

cheungseol commented 6 years ago

util.promisify 是 NodeJS version8+版本的新功能,它接受一个函数作为参数,并将函数转换为promise函数。最为结果返回的promise函数自持promise语法(链式)和 async/await 语法。

注意

作为util.promisify参数的函数,需要满足 NodeJS callback 规范:

  1. 函数必需将 callback 作为最后一个参数,
  2. 并且 callback 函数的参数顺序必需满足这样的形式: (err, value) => { // }

示例:

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()