我一直在使用ES6 Promise。
通常,Promise是这样构造和使用的
new Promise(function(resolve, reject){
if (someCondition){
resolve();
} else {
reject();
}
});
但我一直在做下面这样的事情,为了灵活起见,把决心放在外面。
var outsideResolve;
var outsideReject;
new Promise(function(resolve, reject) {
outsideResolve = resolve;
outsideReject = reject;
});
后来
onClick = function(){
outsideResolve();
}
这很好,但是否有更简单的方法来做到这一点?如果不是,这是一个好的实践吗?
我为此写了一个小库。https://www.npmjs.com/package/@inf3rno/promise.exposed
我使用了别人写的工厂方法,但是我也重写了then, catch, finally方法,所以你也可以通过这些方法解决原来的承诺。
在没有外部执行人的情况下解决承诺:
const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");
从外部与执行器的setTimeout赛跑:
const promise = Promise.exposed(function (resolve, reject){
setTimeout(function (){
resolve("I almost fell asleep.")
}, 100000);
}).then(console.log);
setTimeout(function (){
promise.resolve("I don't want to wait that much.");
}, 100);
如果你不想污染全局命名空间,有一个无冲突模式:
const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const promise = createExposedPromise().then(console.log);
promise.resolve("This should show up in the console.");
以防有人来找简化这个任务的util的typescript版本:
export const deferred = <T>() => {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: any) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return {
resolve,
reject,
promise,
};
};
这可以用在。如:
const {promise, resolve} = deferred<string>();
promise.then((value) => console.log(value)); // nothing
resolve('foo'); // console.log: foo