指针
使用 any-promise。 。 。 .
- 保留函数名称
- 利用本地承诺(如果有的话),并试图回到承诺(如:
bluebird - 将调用中的多个参数转换为
Array,也支持通过options.multiArgs - 生成函数从不优化
- 支持回调和承诺样式
另外一个好处是 thrown 自动函数的错误会被承诺抓住 !
API 密码
fn = (fn, 选项)
推动一个函数.
选项
options 是可选的.
-
options.withCallback- 支持召回和许诺风格,默认为false。 。 。 . -
options.multiArgs- 当召回有多个参数时改变行为. 默认为true。 。 。 .true- 将多个参数转换为数组false- 总是用第一个论据Array- 将多个参数转换为有键的对象options.multiArgs
-
将同步函数变成承诺
var thenify = require('thenify');
var somethingAsync = thenify(function somethingAsync(a, b, c, callback) {
callback(null, a, b, c);
});
- 与回调兼容
var thenify = require('thenify');
var somethingAsync = thenify(function somethingAsync(a, b, c, callback) {
callback(null, a, b, c);
}, { withCallback: true });
// somethingAsync(a, b, c).then(onFulfilled).catch(onRejected);
// somethingAsync(a, b, c, function () {});
或用途 thenify.withCallback()
var thenify = require('thenify').withCallback;
var somethingAsync = thenify(function somethingAsync(a, b, c, callback) {
callback(null, a, b, c);
});
// somethingAsync(a, b, c).then(onFulfilled).catch(onRejected);
// somethingAsync(a, b, c, function () {});
- 总是回调第一个参数
var thenify = require('thenify');
var promise = thenify(function (callback) {
callback(null, 1, 2, 3);
}, { multiArgs: false });
// promise().then(function onFulfilled(value) {
// assert.equal(value, 1);
// });
- 将调用参数转换为对象
var thenify = require('thenify');
var promise = thenify(function (callback) {
callback(null, 1, 2, 3);
}, { multiArgs: [ 'one', 'tow', 'three' ] });
// promise().then(function onFulfilled(value) {
// assert.deepEqual(value, {
// one: 1,
// tow: 2,
// three: 3
// });
// });