Skip to content

Instantly share code, notes, and snippets.

@harish2704
Created July 23, 2023 16:42
Show Gist options
  • Select an option

  • Save harish2704/957d40b950f7db817d5457b83d1dab00 to your computer and use it in GitHub Desktop.

Select an option

Save harish2704/957d40b950f7db817d5457b83d1dab00 to your computer and use it in GitHub Desktop.

Revisions

  1. harish2704 created this gist Jul 23, 2023.
    169 changes: 169 additions & 0 deletions async-examples.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,169 @@
    function log(...args) {
    console.log(new Date(), ...args);
    }

    // Compute intensive synchronous task
    function doMatrixMult(n) {
    let out = 1;
    for (let index = 0; index < n; index++) {
    out = out + Math.sin(index);
    }
    log(`Result of computing for ${n} is `, out);
    return out;
    }

    // call back style asynchronous task
    function asyncTask1({ id, wait }, cb) {
    log("Task with id = ", id, " is starting");
    setTimeout(function () {
    log(`task with id ${id} is done`);
    if (id % 2 === 0) {
    cb(null, `taks ${id} done`);
    } else {
    cb(new Error(`task ${id} failed`));
    }
    }, wait * 1000);
    }

    // call back style asynchronous task converted to promise.
    // It is equivalent to an async function
    function asyncTaskPromise(arg1) {
    return new Promise(function (resolve, reject) {
    asyncTask1(arg1, function (err, res) {
    if (err) {
    return reject(err);
    }
    return resolve(res);
    });
    });
    }

    // An async function ( or promise ) is converted back to callback style async function
    function asyncTaskPromiseCbStyle(arg1, cb) {
    asyncTaskPromise(arg1)
    .then(function (res) {
    cb(null, res);
    })
    .catch(function (err) {
    cb(err);
    });
    }

    /* Example cases */

    function promiseChainExample() {
    // Example of promise chain.
    asyncTaskPromise({ id: 8, wait: 2 })
    .then(function () {
    return asyncTaskPromise({ id: 5, wait: 1 }).catch(function (err) {
    log("Promise 5 failed but ook");
    });
    })
    .then(function () {
    asyncTaskPromise({ id: 4, wait: 5 })
    .then(function () {
    doMatrixMult(110000);
    })
    .catch((err) => {
    console.log("Error at promise 4", err);
    });

    return asyncTaskPromise({ id: 6, wait: 2 });
    })
    .then(function () {
    doMatrixMult(7000);
    })
    .catch(function (err) {
    log("Error occured", err);

    log("All tasks completed");
    });
    }

    // asynchronous function
    async function async_sum(a, b) {
    return a + b;
    }

    // equivalent of the above function.
    function promise_sum(a, b) {
    return new Promise(function (resolve, reject) {
    resolve(a + b);
    });
    }

    // normal function
    function sum(a, b) {
    return a + b;
    }

    async function asyncAwaitExample() {
    let x = sum(3, 2);
    log("a+b", x + 1);
    x = async_sum(3, 2);
    log("a+b", x + 1);
    x = promise_sum(3, 2);
    log("a+b", x + 1);
    let y = await promise_sum(8, 9);
    console.log("y is ", y);
    try {
    await asyncTaskPromise({ id: 2, wait: 2.0 });
    await asyncTaskPromise({ id: 7, wait: 0.1 });
    await asyncTaskPromise({ id: 4, wait: 1.5 });
    await asyncTaskPromise({ id: 8, wait: 0.5 });
    await asyncTaskPromise({ id: 10, wait: 0.2 });
    } catch (error) {
    log("error at ", error);
    }
    }

    function parallelPromiseExample() {
    Promise.all([
    asyncTaskPromise({ id: 2, wait: 2.0 }),
    asyncTaskPromise({ id: 4, wait: 1.5 }),
    asyncTaskPromise({ id: 8, wait: 0.5 }),
    asyncTaskPromise({ id: 10, wait: 0.2 }),
    asyncTaskPromise({ id: 7, wait: 0.1 }),
    ])
    .then(function (items) {
    log("All promises completed", items);
    })
    .catch(function (err) {
    log("Something went wrong", err);
    });
    }

    function callBackSyleExample() {
    try {
    asyncTask1({ id: 8, wait: 2 }, function (err) {
    if (err) {
    throw err;
    }

    asyncTask1({ id: 2, wait: 1 }, function (err) {
    if (err) {
    throw err;
    }
    asyncTask1({ id: 4, wait: 5 }, function (err) {
    if (err) {
    throw err;
    }
    doMatrixMult(11000);
    });
    asyncTask1({ id: 3, wait: 2 }, function (err) {
    if (err) {
    throw err;
    }
    doMatrixMult(7000);
    });
    });
    });
    } catch (err) {
    log("Error occured", err);
    log("All tasks completed");
    }
    }
    // callBackSyleExample();
    // promiseChainExample();
    // parallelPromiseExample();
    asyncAwaitExample()