使用ES6承诺,如何在不定义解决承诺的逻辑的情况下创建承诺?这是一个基本示例(某些TypeScript):
var promises = {};
function waitFor(key: string): Promise<any> {
if (key in promises) {
return promises[key];
}
var promise = new Promise(resolve => {
// But I don't want to try resolving anything here :(
});
promises[key] = promise;
return promise;
}
function resolveWith(key: string, value: any): void {
promises[key].resolve(value); // Not valid :(
}
使用其他promise库很容易做到。jQuery的例子:
var deferreds = {};
function waitFor(key: string): Promise<any> {
if (key in promises) {
return deferreds[key].promise();
}
var def = $.Deferred();
deferreds[key] = def;
return def.promise();
}
function resolveWith(key: string, value: any): void {
deferreds[key].resolve(value);
}
我能看到的唯一方法是将resolve函数存储在Promise的执行程序中某个地方,但这似乎很麻烦,而且我不确定确切地在运行此函数时定义了它-它总是在构造时立即运行吗?
谢谢。