Write asynchronous TypeScript with Promises, async functions, and proper typing.
TypeScript fully supports async/await and adds types to Promise.
function fetchUser(id: number): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve(`User #${id}`), 100);
});
}
async function greetUser(id: number): Promise<string> {
const user = await fetchUser(id);
return `Hello, ${user}!`;
}
An async function always returns a Promise. TypeScript infers the resolved type.
async function safeFetch(url: string): Promise<string> {
try {
const res = await fetch(url);
return await res.text();
} catch (err) {
return 'Failed to fetch';
}
}
Run multiple async operations in parallel:
const [a, b] = await Promise.all([fetchUser(1), fetchUser(2)]);
Export an async function named delay that:
ms: number parameterPromise<string>ms milliseconds (using setTimeout inside a new Promise)"done"// Export an async function named 'delay' // Parameters: ms (number) // Returns: Promise<string> that resolves with "done" after ms milliseconds
No test results yet
Click Run Tests or press Ctrl+Enter