Skip to content

Instantly share code, notes, and snippets.

@gr2m
Created September 4, 2014 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gr2m/5ad1186046c9f68e8a33 to your computer and use it in GitHub Desktop.
Save gr2m/5ad1186046c9f68e8a33 to your computer and use it in GitHub Desktop.
How to achive the logic below with the native JavaScript Promise implementation?
var requestPromise;
function getCurrentState() {
// prevent sending multiple GET requests to /state.json. If one is pending, return its promise
if (requestPromise.isPending()) return requestPromise;
requestPromise = ajaxRequestReturningPromise('GET', '/state.json');
return requestPromise;
}
promise1 = getCurrentState()
promise2 = getCurrentState()
// promise1 & promise2 send only one GET /state.json
@jaz303
Copy link

jaz303 commented Sep 4, 2014

function statusUpdater() {
    var pending = null;
    return function() {
        if (!pending) {
            pending = ajax("...");
            ajax.then(function() {
                pending = null;
            });
        }
        return pending;
    }
}

var getStatus = statusUpdater();

getStatus().then(...);
getStatus().then(...);

@gr2m
Copy link
Author

gr2m commented Sep 4, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment