0

I am having the below call which takes a token and makes an API call and returns another token

export default (token, id) => {
  if (map[id]) {
    return Promise.resolve(map[id]?.token);
  }
  axios
    .post(
      `https://**********`,
      { id },
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    .then(response => {
      const { token } = response;
      map[id] = {
        ...response,
      };
      return token;
    });
};

for the 1st time, I have 5-10 APIs calling this method which makes the individual token API calls because at the 1st moment there is nothing set in the map. Hence individual token call is made until the map is set. I want to reduce the number of token API calls, i.e. make all the API calls wait until the 1st token API call gets a response and sets it in the map.

Varun Sukheja
  • 4,239
  • 3
  • 33
  • 59
  • `const token = (await axios.post(.....)).data;`. Currently `return token` returns the token to... nothing (except to the "then" callback who doesn't do anything with it). `if (map[id])` you return something, otherwise you don't return anything. – Jeremy Thille Feb 22 '21 at 16:47

1 Answers1

-1

Store the promise in the Map:

 if(!map[id])
   map[id] = axios.post(/*...*/).then(/*...*/);
 return map[id];
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120