JavaScript - running only one Promise for multiple

2019-05-11 05:48发布

问题:

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.

回答1:

Sure, this is pretty easy to accomplish

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
}

Which lets you do:

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