In this brief post you will look at how to write code that uses Javascript promise & async/await with simple code samples. This post presents a problem of how to find an element in an array with code for functions that show how to do that using a Javascript promise followed by async/await. This is followed by code samples on how to invoke this code and print either a successful response or an error to console.

Javascript Promise & async/await

I will be honest, as hard as it can be to read, most of the times I prefer creating a promise object as opposed to using async/await. I mean, there is something about creating a new Promise object, doing a set of operations in it and then returning the result via the resolve function. It is harder to read but personally I just find it a bit elegant. Have a look at some pseudocode

function doSomething() {
    return new Promise((resolve, reject) => {
        if some condition is true:
            resolve with value
        else if some condition is false: 
            reject with error 
    })
}

I like the above, but I cannot deny reading async/await is just heaps easier,

async function doSomething() {
    if some condition is true:
        resolve with value
    else if some condition is false: 
        throw error
}

Javascript Promise

function findElemInArrayPromise(stringArr, queryStr) {
    return new Promise((resolve, reject) => {
        if(typeof queryStr !== 'string' || !queryStr) {
            reject("Incorrect queryStr passed");
        }
        let result = null;
        stringArr.forEach(element => {
            if(element.toLowerCase() === queryStr) {
                resolve(result);
            }
        });
        resolve(null);
    });
}

Code to call the function

const arr = ["one", "two", "three", "four"];

findElemInArrayPromise(arr, "one").then(res => {
    if(res) {
        console.log(`1. Element found ${res}`);
    } else {
        console.log(`2. Element not found ${res}`);
    }
}).catch(err => {
    console.log(err);
})

findElemInArrayPromise(arr, "").then(res => {
    if(res) {
        console.log(`3. Element found ${res}`);
    } else {
        console.log(`4. Element not found ${res}`);
    }
}).catch(err => {
    console.log(err);
})

Javascript async/await

Rewrite the above function using async/await

async function findElemInArrayAsync(stringArr, queryStr) {
    if(typeof queryStr !== 'string' || !queryStr) {
        return Promise.reject("Incorrect queryStr passed");
    }
    let result = null;
    await stringArr.forEach(element => {
        if(element.toLowerCase() === queryStr) {
            result = element;
        }
    });
    return result;
}

Code to call the function

findElemInArrayAsync(arr, "two").then(res => {
    if(res) {
        console.log(`5. Element found ${res}`);
    } else {
        console.log(`6. Element not found ${res}`);
    }
}).catch(err => {
    console.log(err);
});

findElemInArrayAsync(arr).then(res => {
    if(res) {
        console.log(`7. Element found ${res}`);
    } else {
        console.log(`8. Element not found ${res}`);
    }
}).catch(err => {
    console.log(err);
})

Conclusion

Hope you found this blogpost useful and you feel more confident writing code using Javascript promise & async/await.

If you find any of my posts useful and want to support me, you can buy me a coffee 🙂

https://www.buymeacoffee.com/bhumansoni

While you are here, maybe try one of my apps for the iPhone.

Products – My Day To-Do (mydaytodo.com)

Have a read of some of my other posts on AWS

Deploy NodeJS, Typescript app on AWS Elastic beanstalk – (mydaytodo.com)

How to deploy spring boot app to AWS & serve via https – My Day To-Do (mydaytodo.com)

Some of my other posts on Javascript …

What is Javascript event loop? – My Day To-Do (mydaytodo.com)

How to build a game using Vanilla Javascript – My Day To-Do (mydaytodo.com)

Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)

Java Spring Boot & Vanilla Javascript solution – My Day To-Do (mydaytodo.com)

Vanilla Javascript: Create Radio Buttons (How-To) – Bhuman Soni (mydaytodo.com)

Categories: Javascript

0 Comments

Leave a Reply

Avatar placeholder