Using await to Replace .then()

by dshilkret

HTML

<div>
With async/await, await replaces .then(). The function execution waits for the promise to resolve or reject. The try/catch block is used to handle errors instead of .catch().
</div>

JavaScript

const fetchData = async () => {
    return new Promise(resolve => setTimeout(() => resolve("Fetched data"), 1000));
};

const processData = async data => {
    return new Promise(resolve => setTimeout(() => resolve(`${data} and processed`), 1000));
};

const runAsyncFunctions = async () => {
    try {
        const data = await fetchData();
        const processedData = await processData(data);
        console.log(processedData);
    } catch (error) {
        console.error("Error:", error);
    }
};

runAsyncFunctions();