Fundamentals



asynchronous operation



promises and async/awaits


  1. then() /catch()
  2. async, await

then() /catch()


// Promise-based function

const promiseFunction = (): Promise<string> => {
    return new Promise((resolve, reject) => {
        const success = true;

        setTimeout(() => {
            if (success) {
                resolve("done");
            } else {
                reject(new Error("Something went wrong"));
            }
        }, 1000);
    });
};

usage


promiseFunction()
    .then(result => {
        console.log("Success:", result);
    })
    .catch(error => {
        console.error("Error:", error.message);
});

async, await


// Async function calling the promise

async function myFunc() {
    try {
        const result = await promiseFunction();
        console.log("Success:", result);
    } catch (error) {
        console.error("Error:", (error as Error).message);
    }
}
async function fetchData() {
    return "data"; //Even though fetchData just returns a string, it implicitly returns a Promise that resolves to "data".
}