DEV Community

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

Posted on

2 1

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)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay