扩展承诺
保证是伟大的! 但是,他们会更好吗?
安装
npm install @braintree/extended-promise
为什么?
这个库是为了与不易被承诺包裹的API合作而开发的,例如踢出一个在事件听众召回内解决的承诺.
在写这首诗之前,我们保留了对基础承诺的引用,并提及 resolve编号 :reject 功能,以便日后解决并拒绝:
// without this lib
class MyCustomObject {
constructor() {
this._promise = new Promise((resolve, reject) => {
this._resolveFunction = resolve;
this._rejectFunction = reject;
});
}
asyncProcess() {
// do something very async that's not easily wrapped in a promise
if (success) {
this._resolveFunction(data);
} else {
this._rejectFunction(new Error("fail"));
}
}
methodRelyingOnResultOfPromise() {
return this._promise;
}
}
相反,我们可以省略一则只提及承诺,然后直接解决或拒绝承诺:
// with this lib
class MyCustomObject {
constructor() {
this._promise = new ExtendedPromise();
}
asyncProcess() {
// do something very async that's not easily wrapped in a promise
if (success) {
this._promise.resolve(data);
} else {
this._promise.reject(new Error("fail"));
}
}
methodRelyingOnResultOfPromise() {
return this._promise;
}
}
当承诺解析/ 拒绝时, 添加钩子以运行
该对象还提供 onResolve 财务报告和审定财务报表 onReject 可在即时传递的钩子 :
var promise = new ExtendedPromise({
onResolve(data) {
return someFunctionToTransformData(data);
},
onReject(error) {
// decide if you want to catch the error
return someFallbackDataInstead;
// or if you want to continue through with the rejection
return Promise.reject(error);
},
});
禁止未经处理的拒绝承诺警告
使用的好处之一 ExtendedPromise 即你可以把承诺对象传到周围 并同步捕捉错误 然而,这可以导致节点或浏览器假设,当承诺在你添加了拒绝处理器之前就拒绝,那么承诺是完全不处理的. 为了压制这些警告,请添加 suppressUnhandledPromiseMessage 选项,当即时定义:
var promise = new ExtendedPromise({
suppressUnhandledPromiseMessage: true,
});
// do async stuff that results in the promise rejecting
// and don't worry about Node or the browser being
// angry about it
promise.catch(function (err) {
// handle this later
});
你也可以在全球为所有人设定 ExtendedPromise编号:
ExtendedPromise.suppressUnhandledPromiseMessage = true;
var promise = new ExtendedPromise();
// do async stuff that results in the promise rejecting
// and don't worry about Node or the browser being
// angry about it
promise.catch(function (err) {
// handle this later
});
如果设定全球财产和实例财产,它将使用实例财产.
用作正常的许诺
何时 ExtendedPromise 以函数即时化,它将返回基本承诺。 这个 resolve 财务报告和审定财务报表 reject 实例方法不应使用这种方法。 这样做只是为了使移徙更容易使用扩展承诺.
var promise = new ExtendedPromise(function (resolve, reject) {
// if success
resolve('value');
// if failure
reject(new Error('err'));
});
promise.then(val => {
// handle result
}).catch(err => {
// handle error
})
使用自定义承诺执行
如果您的环境不支持承诺, 您可以设置承诺对象直接用于对象 .
const PromisePolyfill = require("promise-polyfill");
ExtendedPromise.setPromise(PromisePolyfill);
发展
运行测试 :
npm test