promises_在Promisify节点中使用Promises而不是回调

promises

One of the reasons we love promises so much is because they allows us to avoid the infamous callback hell that we've all experienced in these early days of Node.js.  When I see an API that doesn't use the promise pattern, I get annoyed.  Luckily I've found promisify-node, a module that wraps functions or objects in a promise wrapper so you can avoid the callback mess!

我们之所以承诺如此之多的原因之一是,因为它们使我们能够避免在Node.js成立初期我们都经历过的臭名昭著的回调地狱。 当我看到一个不使用Promise模式的API时,我很生气。 幸运的是,我找到了promisify-node ,一个将函数或对象包装在promise包装器中的模块,这样您就可以避免回调混乱!

There are a few different ways to use promisify-node.  The first is wrapping a single function in the promise:

有几种使用promisify-node的方法。 首先是在promise中包装一个函数:


var promisify = require('promisify-node');

function async(callback) {
  callback(null, true);
}

// Convert the function to return a Promise.
var wrap = promisify(async);

// Invoke the newly wrapped function.
wrap().then(function(value) {
  console.log(value === true);
});


You could even recursively wrap a Node.js module's functions:

您甚至可以递归包装Node.js模块的功能:


var promisify = require('promisify-node');
var fs = promisify('fs');

// This function has been identified as an asynchronous function so it has
// been automatically wrapped.
fs.readFile('/etc/passwd').then(function(contents) {
  console.log(contents);
});


And then you can wrap an object's methods:

然后可以包装对象的方法:


var promisify = require('promisify-node');

var myObj = {
  myMethod: function(a, b, cb) {
    cb(a, b);
  }
};

// No need to return anything as the methods will be replaced on the object.
promisify(myObj);

// Intentionally cause a failure by passing an object and inspect the message.
myObj.myMethod({ msg: 'Failure!' }, null).then(null, function(err) {
  console.log(err.msg);
});


Since many front-end APIs are moving to Promise-based APIs, it would be awesome to use something like Promisify to get into the habit of using them on both the server and client sides. Be warned, however, that this module uses a snippet of code to detect function arguments. If you don't use a frequently-used callback argument name, like callback or cb, the promisify-wrapped function may not work correctly.

由于许多前端API正在迁移到基于Promise的API,因此使用Promisify之类的东西来养成在服务器端和客户端都使用它们的习惯真是太棒了。 请注意,此模块使用代码片段来检测函数自变量 。 如果您不使用常用的回调参数名称,例如callbackcb ,则promisify-wrapped函数可能无法正常工作。

翻译自: https://davidwalsh.name/promises-callbacks-promisifynode

promises

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值