我想让对象请求JavaScript承诺,但我不希望它们创建单独的promise.我想要实现的逻辑如下 – 检查一个承诺是否未决,只有不承诺,创建一个新的承诺.这可能吗?根据文档,我无法检查承诺的状态,我只能在它满满后处理它但我不想为每个承诺请求调用处理程序,如果一个Promise的回调可以,我不想运行多个Promises回应所有过去的请求……
我试图以这种方式解决的问题是从外部服务器获取数据并在接收后通过事件将其广播到多个对象.
解决方法:
当然,这很容易实现
var _p = null; // just a cache
function batchRequests(fn){
if(_p != null) return _p; // if we have an in-flight request, return it
_p = fn(); // otherwise start a new action
_p.then(function(){ _p = null; }, // delete cache on resolve
function(){ _p = null; }); // even on failure
return _p; // return the new in-flight request
}
这可以让你做到:
function delay(){ // just for example, simulate a request
return new Promise(function(resolve){ setTimeout(resolve, 1000); });
}
var batched = function(){ return batchRequests(delay); };
batched().then(function(){ console.log("All these"); });
batched().then(function(){ console.log("execute after"); });
batched().then(function(){ console.log("one second, at the same time"); });