JavaScript – 仅为多个请求运行一个Promise

我想让对象请求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"); });

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...