仅为多个请求运行一个Promise

仅为多个请求运行一个Promise

本文介绍了JavaScript - 仅为多个请求运行一个Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对象请求JavaScript承诺,但我不希望它们创建单独的promise。我想要实现的逻辑如下 - 检查一个承诺是否未决,只有不承诺,创建一个新的承诺。这可能吗?根据文档,我无法检查承诺的状态,我只能在它满满后处理它但我不想为每个承诺请求调用处理程序,如果一个Promise的回调可以,我不想运行多个Promises响应所有过去的请求...

I want to have objects request a JavaScript promise, but I don't want them to create separate promises. The logic I want to achieve is as follows - check if a promise is pending, and only if not, create a new promise. Is this possible? According to documenation I can't check status of a promise, I can only handle it after it's fullfilled but I don't want to call handlers for every promise request, and I don't want to run multiple Promises if one Promise's callback can response to all past requests...

我试图以这种方式解决的问题是从外部服务器获取数据并在收到数据后通过事件将其广播到多个对象。

The problem I'm trying to solve this way is fetching data from outside server and broadcasting it through event to multiple objects after receiving it.

推荐答案

当然,这很容易实现

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"); });

这篇关于JavaScript - 仅为多个请求运行一个Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:58