cal*_*lum 13 javascript promise bluebird
我想要一个等待直到then它运行之前被调用的承诺.也就是说,如果我从未真正打过电话then,承诺将永远无法运行.
这可能吗?
mea*_*gar 13
创建一个在第一次调用时创建并返回promise的函数,但在每次后续调用时返回相同的promise:
function getResults() {
if (getResults.results) return getResults.results;
getResults.results = $.ajax(...); # or where ever your promise is being built
return getResults.results;
}
Run Code Online (Sandbox Code Playgroud)
Promise不能以支持延迟加载的方式工作.Promise由异步代码创建,以便传达结果.在调用异步代码之前,根本就没有承诺.
你当然可以编写一个类似于promise的对象来执行惰性调用,但生成这些promise的代码会有很大不同:
// Accepts the promise-returning function as an argument
LazyPromise = function (fn) {
this.promise = null;
this.fn = fn
}
LazyPromise.prototype.then = function () {
this.promise = this.promise || fn();
this.promise.then.apply(this.promise, arguments)
}
// Instead of this...
var promise = fn();
// You'd use this:
var promise = new LazyPromise(fn);
Run Code Online (Sandbox Code Playgroud)
在这种罕见的使用中,最好使实际创建的承诺变得懒惰(如上例中所示),而不是试图让承诺自己负责延迟评估.
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |