DEV Community

Discussion on: Handling async await

 
jaakofalltrade profile image
Jaako • Edited

Ok, the problem is you cannot pass a value to emailStatus coming from the .then method:

I have encountered this problem before but I forgot how I got to the bottom of it.
This post should help.

var emailStatus; // You cannot pass a value here
_verifyEmail(User).then(async res => {
        // Coming from here, the value inside this scope is only contained 
        // inside this scope correct me if I'm wrong.
        emailStatus = await res;
        console.log(`res: ${res}`);
    });

I think there are two ways to solve this problem,

The first one requires you to add an async in _verifyUser:


async function _verifyUser(User){
    var emailStatus = await _verifyEmail(User); // Here
    const passwordStatus = _verifyPassword(User);
    const nameStatus = _verifyName(User);
    const surnameStatus = _verifySurname(User);

    console.log(`email status: ${emailStatus}`);
    console.log(`password status: ${passwordStatus}`);
    console.log(`name status: ${nameStatus}`);
    console.log(`surname status: ${surnameStatus}`);

    if(emailStatus === 400 || passwordStatus === 400 || nameStatus === 400 || surnameStatus === 400)
        return 400;
    else
        return 202;
}

The second one is a little bit experimental because i don't know if it will work:
Edit: Come to think of it this will not work, it will only return a promise I think.

function _verifyUser(User){
    // here
    var emailStatus = _verifyEmail(User).then(async res => {
        return emailStatus = await res;
    });
    const passwordStatus = _verifyPassword(User);
    const nameStatus = _verifyName(User);
    const surnameStatus = _verifySurname(User);

    console.log(`email status: ${emailStatus}`);
    console.log(`password status: ${passwordStatus}`);
    console.log(`name status: ${nameStatus}`);
    console.log(`surname status: ${surnameStatus}`);

    if(emailStatus === 400 || passwordStatus === 400 || nameStatus === 400 || surnameStatus === 400)
        return 400;
    else
        return 202;
}