Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get properties from previously resolved promise?

I have an async function that returns an object after running fetch and .json(). I want to have more than one callback that take the object as input. Since I need to chain .then() to call the callback, I need to run the fetching function each time.

Is there a way to fetch once, and then have the callbacks do their thing with the output without having to refetch?

async function getData(){
  const response = await fetch('api-url');
  return await response.json();
}

function foo(data){
  // do stuff
}

function bar(data){
  // do stuff
}

const doFoo = getData().then(foo) // I don't want to run getData()
const doBar = getData().then(bar) // each time

I guess, I can save the output to a cache, but is there a way to do it with promises?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Any time you want to generate a value once and then use it multiple times: Store it in a variable.

const data = getData();
data.then(foo);
data.then(bar);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading