我们如何在 node.js 包中使用 promise

How can we use promise in node.js packages

当我们为 node.js 编写模块时,我们使用回调函数。我在 javascript 中学习了 promises,我想在 node.js 模块中使用。我们可以使用 promises 而不是回调函数吗?如果可以,怎么做?

注意:通过节点模块文件中的函数(你知道 exports.some_func),我们做了一些事情,我们可以用回调发回信息。我们可以使用 promise 代替那个回调吗?

Can we use promise instead of that callback ?

是的,您可以只 return 一个承诺,并确保在异步操作时该承诺是 resolved/rejected 并具有正确的 value/reason,而不是在您的导出函数中接受回调完成了。

这是一个例子:

假设您有一个用于读取文件的模块接口,那么您可以拥有该接口return这样的承诺:

// myFileModule.js
const fs = require('fs');

module.exports.getFile = function(filename, options) {
    return new Promise(function(resolve, reject) {
        fs.readFile(filename, options, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

调用者会像这样使用它:

const myFiles = require('myFileModule.js');

myFiles.getFile('temp.txt').then(function(data) {
    // process data here
}, function(err) {
    // got an error here
});