OskaDev

OskaDev

Promise and A+ ( Async Await )

Did you know promise and async is fully compatible?

Promises

In promises, some of them call it callback hell because of the syntax keep repeating callback like and until the end of the async operation. Here come with an example.

() => {
    var promise = new Promise((resolve, reject) => {
        try {
            // async codeblock
            resolve(result);
        }
        catch (e) {
            reject(e);
        }
    });

    promise.then(
        (result) => {
            // result is returning and async operation run complete.
        },
        (rejected) => {
            // rejected something wrong when running async operation
        }
    ).catch(
        (error) => {
            // unhandled error occurs when running async opeartion
        }
    );
}

With this example, you able see that promise code block is quite long when running an async operation, try to think what if more complex async operation required to run, like you need to get data from backend and then get data from other 3rd party and then checking and then only apply. With all of these action you will see that code is quite messy.

Async/Await

But what these in async/await syntax? async/await has break this callback hell by using reserved keyword async at method code block and await inside function body to declare method is async action ( will be automatically return Promise ) and await declare action need to wait for async opeartion complete.

samplePromise: async () => {
    var promise = new Promise((resolve, reject) => {
        try {
            // async codeblock
            resolve(result);
        }
        catch (e) {
            reject(e);
        }
    });

    try {
        // Must remeber he is not function. so just called like this.
        const result = await promise;
        const result2 = await promise;
        const result3 = await promise;
        const result4 = await promise;
    }
    catch (ex) {
        // error handling code block
    }
}

As you have seen, async/await codeblock is shorter and more clear for but i still suggest if you new into javascript please take time to know about promises & async/await still important to you for future develop & develop with teams. As of me, i allowed my mates use Promise / async&await since everyone have own choice due to backend part used microservices so able to do this if not some async/await and some promise would be messy.

Another important part you need to know.

Async/Await & Promise Compability

All of the functions with async keyword would automatically return Promise so you can solve it via async/await or promises. So more easierly to work with your mates without conflict, clashing or anything on syntax.

async function sample()
{
 return "ABC";
}

function sample()
{
 return new Promise((resolve, reject) => resolve("ABC"));
}

sample().then(result => console.log(result));
await sample();

[OUTPUT]
ABC
ABC

Stream based async action

Stream based async action would be some problem if you return without Promise in async function. You will see your code has not been waited. This is my personal experience & problem meet when building async/await codeblock.

async function upload() {
    /* Sample stream */
    const stream = file.createWriteStream({
        validation: 'crc32c',
        metadata: {
            contentType: 'image/png'
        }
    });

    stream.on('error', error => {
        throw {
            message: `Error occurs when uploading image to storage`,
            stack: error
        };
    });

    stream.on('finish', () => {
        return {
            message: `Image uploaded succesfully.`,
            result: fileId
        };
    });

    stream.end(base64);
}

await upload();

[OUTPUT]
undefined

Normally you see the code doesn't have problem but when run the code will go through and never wait and unable get return result. Why? As i above said return value will automatically apply Promise but for stream it apply at the return value part so it running inside stream event listener instead of the function block so will keep going until end of the code and return undefined. For such situation you need to apply the Promise yourself instead of auto apply by async keyword.

async function upload() {
    const stream = file.createWriteStream({
        validation: 'crc32c',
        metadata: {
            contentType: 'image/png'
        }
    });

    return new Promise((resolve, reject) => {
        stream.on('error', error => {
            reject({
                message: `Error occurs when uploading image to storage`,
                stack: error
            });
        });
        stream.on('finish', () => {
            resolve({
                message: `Image uploaded succesfully.`,
                result: fileId
            });
        });
        stream.end(base64);
    });
}

await upload();

[OUTPUT]
{
    message: `Image uploaded succesfully.`,
    result: fileId
}

Run async/await inside Promise for Stream Based Async Action

In stream based async action, how we run async/await instead of promise inside promise? Just apply async to Promise.

async function log() {
    console.log('ABC');
}

async function run() {
    return new Promise(async (resolve, reject) => {
        await log();
        await log();
        resolve('CBA');
    });
}

await run();

[OUTPUT]
ABC
ABC
CBA

Stream based async action codeblock work with ReactiveX

Since reactiveX is popular in many language and useful to development so as RX said they used stream like so you able apply stream based async action code block work with ReactiveX library code also.

async function run() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Is me')
        }, 1000);
    });
}

await run();

[OUTPUT]
Is me  // <-- after 1000ms
}

function sample2() {
    return new Promise(resolve => resolve('ABC'));
}

await sample1();
await sample2();

[OUTPUT]
ABC
ABC

Parallel async operation

As example above all of the action run seperately but you also able to let them run parallel by using build in function Promise.all.

async function a() {
    return "I'm Oska";
}

async function b() {
    return "I'm student in MMU";
}

async function c() {
    return "I'm a developer";
}

async function run() {
 // Promise.all returning array of results so you can either use one of them.
 /* (1) */ const [first, sec, third] = await Promise.all([a(), b(), c()]);
 /* (2) */ const results = await Promise.all([a(), b(), c()]);

    console.log(`${first} ${sec} ${third}`);
    /* OR */
    console.log(`${results[0]} ${results[1]} ${results[2]}`);
}

await run();

[OUTPUT]
I'm Oska
I'm student in MMU
I'm a developer
 
Share this