DEV Community

Cover image for TS async data creation helper function
Jamie Neubert Pedersen
Jamie Neubert Pedersen

Posted on

TS async data creation helper function

I have created a neat little helper function to create asynchronous data of synchronous data. I usually use it for mock data.

async function promiseOf<T>(data: T): Promise<T> {
  return new Promise(resolve => resolve(data));
}
Enter fullscreen mode Exit fullscreen mode

This simulates data being fetched. Because it uses generics, the data passed in will be available in Intellisense.

It can also easily be extended to include a mocked "latency"

async function promiseOf<T>(data: T, latency = 0): Promise<T> {
  return new Promise(resolve => setTimeout(resolve(data), latency));
}
Enter fullscreen mode Exit fullscreen mode

Let me know if you find this helpful.

Top comments (0)