0

I wrote an async-await functions using Promise returning functions. However, I'm not sure if the behavior I desire is being implemented. On that token, I've tried researching ways to see if my code is behaving asynchronously but to no avail. Without further ado, here is my code :

sum = 0

function checkEven(num) {
    return new Promise((res,rej) => {
        if(typeof num === 'number'){
            if(num % 2 == 0){
                res(true)
                console.log(`Currently processing ${num}`)
            } else {
                res(false)
            }
        } else {
            rej(`${num} is not a number!`)
        }
    })
}

function addToSum(bool, num) {
    return new Promise((res,rej) => {
        if(bool){
            sum += num
            res(`Adding ${num} to sum. Sum is now ${sum}.`)
        }else{
            res(`Not adding ${num} to sum. Sum is now ${sum}.`)
        }
        rej("hi")
    })

}

async function addEvenNumbersOnly(n1,n2) {
    try{
        const first = await checkEven(n1)
        const second = await checkEven(n2)
        const addFirst = await addToSum(first, n1)
        console.log(addFirst)
        const addSecond = await addToSum(second, n2)
        console.log(addSecond)
        console.log(sum)
    } catch (err){
        console.log(err)
    }
    
}

addEvenNumbersOnly(100,102)

Hopefully the code is self explanatory; I take two numbers and check their evenness, if they're even I add them to a global sum, otherwise I don't.

The asynchronous behavior in my head is here:

const first = await checkEven(n1)
const second = await checkEven(n2)

Does checkEven(n2) execute while checkEven(n1) is being processed?

const addFirst = await addToSum(first, n1)
const addSecond = await addToSum(second, n2)

Similarly, does addToSum(second, n2) start execution while addToSum(first, n1) is being executed?

ameteur
  • 31
  • 2
  • Everything in your code is synchronous, there's nothing that could be done in the background. Do not add promises or `async`/`await` to such code. – Bergi May 29 '22 at 21:16
  • "*Does `checkEven(n2)` execute while `checkEven(n1)` is being processed?*" - no. a) because it does execute synchronously, but also b) because you've got an `await` between them! – Bergi May 29 '22 at 21:17

0 Answers0