• original {Function}
    • 返回: {Function}

    传入一个遵循常见的错误优先的回调风格的函数(即以 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。

    1. const util = require('util');
    2. const fs = require('fs');
    3. const stat = util.promisify(fs.stat);
    4. stat('.').then((stats) => {
    5. // 使用 `stats`。
    6. }).catch((error) => {
    7. // 处理错误。
    8. });

    或者,等效地使用 async function:

    1. const util = require('util');
    2. const fs = require('fs');
    3. const stat = util.promisify(fs.stat);
    4. async function callStat() {
    5. const stats = await stat('.');
    6. console.log(`该目录归 ${stats.uid} 拥有`);
    7. }

    如果存在 original[util.promisify.custom] 属性,则 promisify 将会返回其值,参见[自定义的 promise 化函数][Custom promisified functions]。

    promisify() 在所有情况下都会假定 original 是一个以回调作为其最后参数的函数。 如果 original 不是一个函数,则 promisify() 将会抛出错误。 如果 original 是一个函数但其最后一个参数不是一个错误优先的回调,则它将仍会传入一个错误优先的回调作为其最后一个参数。

    除非特殊处理,否则在类方法或使用 this 的其他方法上使用 promisify() 可能无法正常工作:

    1. const util = require('util');
    2. class Foo {
    3. constructor() {
    4. this.a = 42;
    5. }
    6. bar(callback) {
    7. callback(null, this.a);
    8. }
    9. }
    10. const foo = new Foo();
    11. const naiveBar = util.promisify(foo.bar);
    12. // TypeError: Cannot read property 'a' of undefined
    13. // naiveBar().then(a => console.log(a));
    14. naiveBar.call(foo).then((a) => console.log(a)); // '42'
    15. const bindBar = naiveBar.bind(foo);
    16. bindBar().then((a) => console.log(a)); // '42'