Skip to main content

Promise awaited | Typescript

  • Promise awaited | Typescript


// Example 1: Basic Promise and Await

function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

async function example1() {
console.log("Before delay");
await delay(2000);
console.log("After delay");
}

example1();

// Example 2: Handling Promise Rejection

function fetchData(): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() < 0.5;
if (success) {
resolve("Data fetched successfully");
} else {
reject("Failed to fetch data");
}
}, 2000);
});
}

async function example2() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}

example2();

// Awaited - tipo para remover o promise de um tipo
const retorno: Awaited<ReturType<typeof fetchData>> = await fetchData()