JS回调承诺组合模式:好的还是坏的做法



我正在编写一些将提供异步方法的库,我希望用户能够根据自己的偏好使用经典回调或现代承诺。

我给每种方法编码了两个版本,分别命名为"myMethod"one_answers"myMethodPromise",然后我想到了一个想法:

为什么不编写一个结合这两种模式的方法呢

一个带有可选回调参数的方法,如果没有提供,则该方法返回promise而不是调用回调。

这是一个好的做法吗

// Promise-callback combined pattern method
function myAsyncMethod ( callback = null ) {
	if(callback) {
	var result = "xxx";
	// Do something...
		callback(result);
} else {
	  return(new Promise((res, rej) => {
var result = "xxx";
// Do something...
res(result);
}))
}
}
// Usage with callback
myAsyncMethod((result)=>document.getElementById('callbackSpan').innerHTML = result);
// or with promise
myAsyncMethod().then((result) => document.getElementById('promiseSpan').innerHTML = result);
<p>
Result with callback : <span id="callbackSpan"></span>
</p>
<p>
Result with promise : <span id="promiseSpan"></span>
</p>

**

您可以按照request-promise模块操作。它们将request module包裹在request-promise内。并且只编写了一个小的配置文件来分配所有可承诺的方法

更多信息:https://github.com/request/request-promise/blob/master/lib/rp.js

您还可以使用node promisify承诺方法

const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});

//请求模块

Bluebird.config({cancellation: true});
configure({
request: request,
PromiseImpl: Bluebird,
expose: [
'then',
'catch',
'finally',
'cancel',
'promise'
// Would you like to expose more Bluebird methods? Try e.g. `rp(...).promise().tap(...)` first. `.promise()` returns the full-fledged Bluebird promise.
],
constructorMixin: function (resolve, reject, onCancel) {
var self = this;
onCancel(function () {
self.abort();
});
}
});
request.bindCLS = function RP$bindCLS() {
throw new Error('CLS support was dropped. To get it back read: https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage');
};

最新更新