-2

I have this function:

const buildDataSource = (): Promise<Data> => {
  const data = fetch('https://jsonplaceholder.typicode.com/posts')
    .then((response) => response.json())
    .then((items) => items.map((item: RawDataItem, idx: number) => ({
      key: idx,
      randStr: item.title.substring(1, 24),
    })));
  return data;
};

And call it with this: const data = buildDataSource();

but data is a resolved promise that includes the data, not the data itself. Where am I going wrong here?

halfer
  • 19,824
  • 17
  • 99
  • 186
Mr. Robot
  • 1,334
  • 6
  • 27
  • 79
  • 3
    That's how asynchronous programming is supposed to work in JavaScript. You have to `.then` the Promise you return wherever you use it. – zero298 Jan 31 '20 at 14:49
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – zero298 Jan 31 '20 at 14:49
  • `fetch` is asynchronous and returns `promise`. You should use `then` to manipulate `data` or consider using `async functions` – Stas Amasev Jan 31 '20 at 14:58
  • You cannot make asynchronous data return in a synchronous manner. – Dan Jan 31 '20 at 15:20

1 Answers1

0

Problem with promises and async in general is that once you start with it you need to put it everywhere up your stack. Basically the function that is consuming your buildDataSource will also have to be async and so on ...

On a different note you should definatelly look async/await because it makes reading async code much easier (your buildDataSource as async):

const buildDataSource = async (): Promise<Data> => {
  const response= await fetch('https://jsonplaceholder.typicode.com/posts');
  const items = await response.json();
  const data = items.map((item: RawDataItem, idx: number) => ({
      key: idx,
      randStr: item.title.substring(1, 24),
    }));
  return data;
}

And then use it like this:

const something = async () => {
   const data = await buildDataSource (); // data here is your list
}
Kaca992
  • 2,211
  • 10
  • 14