JamesYin JamesYin - 4 months ago 8
Javascript Question

Resolve a promise once in a racing time

Here is a Promise:

var getVersion = new Promise(function(resolve){
getVersionAsyn(resolve);
});

Then a lot of http requests depend on that 'version' and the requests send in the same time.

When page initial, a lot of http requests will send to server and the request are depend on 'version'.

How to prevent
getVersion
promise run multiple times?




All right. I down vote myself. Such a idiot question.

Answer

How to prevent getVersion promise run multiple times?

You are already caching the promise and thus the resolved value of the version so getVersionAsyn() only ever gets called once. You can have as many .then() handlers as you want on a promise and all the subsequent once do is just fetch the saved, resolved value out of the promise data structure. They don't "execute" anything else over and over again.

The way this code works:

var getVersion = new Promise(function(resolve){
    getVersionAsyn(resolve);
});

getVersion is a promise and you are already storing it. You can have as many callers as you do this:

getVersion.then(function(version) {
    // access the version here
});

And, getVersionAsyn() will only ever be called just once, the first time. From then on, once the promise has resolved, you will just be accessing the saved resolved value (essentially an automatic cache). It is actually a nice design pattern to use promise for caching and async-retrieved value.

Comments