我们如何在node.js包中使用Promise [英] How can we use promise in node.js packages
问题描述
当我们为node.js编写模块时,我们使用回调函数.我在javascript中学习了promises,我想在node.js模块中使用.我们可以使用promise代替回调函数吗?如果可以,怎么办?
When we write a module for node.js, we use callback functions. I learned promises in javascript and I want to use in node.js module. Can we use promises instead of callback functions ? if we can, how ?
注意:通过节点模块文件中的函数(您知道exports.some_func),我们可以执行某些操作,并且可以使用回调发送回信息.我们可以使用promise代替该回调吗?
note : via function in node module file ( you know exports.some_func ) , we do somethings and we can send back informations with callback . Can we use promise instead of that callback ?
推荐答案
我们可以使用promise代替回调吗?
Can we use promise instead of that callback ?
是的,您可以只返回一个promise,并确保在完成异步操作后以适当的值/原因确保promise被解析/拒绝,而不是在导出的函数中接受回调.
Yes, rather than accepting a callback in your exported function, you can just return a promise and make sure that promise is resolved/rejected with the proper value/reason when the async operation is done.
这是一个例子:
想象一下,您有一个用于读取文件的模块接口,那么您可以让该接口返回如下承诺:
Imagine you have a module interface for reading a file, then you can have that interface return a promise like this:
// 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);
});
});
}
然后,呼叫者会这样使用它:
The caller would then use it like this:
const myFiles = require('myFileModule.js');
myFiles.getFile('temp.txt').then(function(data) {
// process data here
}, function(err) {
// got an error here
});
这篇关于我们如何在node.js包中使用Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!