Alessandro Bertozzi
Alessandro Bertozzi

Reputation: 2941

Async function returning undefined instead of data

I'm doing requests to my API server to authenticate a user, that's not the problem. The problem is that I don't know why my async function doesn't return anything, and I get an error because the data that I want from this function is undefined.

Don't worry if the error management is ugly and in general I can do this better, I'll do that after fixing this problem.

Utils.js class

    async Auth(username, password) {

        const body = {
            username: username,
            password: password
        };

        let req_uuid = '';

        await this.setupUUID()
            .then((uuid) => {
                req_uuid = uuid;
            })
            .catch((e) => {
                console.error(e);
            });

        let jwtData = {
            "req_uuid": req_uuid,
            "origin": "launcher",
            "scope": "ec_auth"
        };

        console.log(req_uuid);

        let jwtToken = jwt.sign(jwtData, 'lulz');

        await fetch('http://api.myapi.cc/authenticate', {
            method: 'POST',
            headers: { "Content-Type": "application/json", "identify": jwtToken },
            body: JSON.stringify(body),
        })
            .then((res) => {
                // console.log(res);
                // If the status is OK (200) get the json data of the response containing the token and return it
                if (res.status == 200) {
                    res.json()
                        .then((data) => {
                            return Promise.resolve(data);
                        });
                    // If the response status is 401 return an error containing the error code and message
                } else if (res.status == 401) {
                    res.json()
                    .then((data) => {
                        console.log(data.message);
                    });
                    throw ({ code: 401, msg: 'Wrong username or password' });
                    // If the response status is 400 (Bad Request) display unknown error message (this sould never happen)
                } else if (res.status == 400) {
                    throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
                }
            })
            // If there's an error with the fetch request itself then display a dialog box with the error message
            .catch((error) => {
                // If it's a "normal" error, so it has a code, don't put inside a new error object
                if(error.code) {
                    return Promise.reject(error);
                } else {
                    return Promise.reject({ code: 'critical', msg: error });
                }
            });
    }

Main.js file

utils.Auth('user123', 'admin')
    .then((res) => {
        console.log(res); // undefined
    });

Upvotes: 2

Views: 2177

Answers (3)

Thiago Barcala
Thiago Barcala

Reputation: 7353

Your Async function must return the last promise:

return fetch('http://api.myapi.cc/authenticate', ...);

or await the result and return it:

var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;

Notice that you don’t need to mix promise syntax (.then) with await. You can, but you don’t need to, and probably shouldn’t.

These two functions do exactly the same thing:

function a() {
    return functionReturningPromise().then(function (result) {
        return result + 1;
    });
}

async function b() {
    return (await functionReturningPromise()) + 1;
}

Upvotes: 2

ossiggy
ossiggy

Reputation: 219

I would try something like this:

const postReq = async (jwtToken) => {
  const body = {
    username: username,
    password: password,
  };

  try {
    const res = await fetch('http://api.myapi.cc/authenticate', {
      method: 'POST',
      headers: { "Content-Type": "application/json", "identify": jwtToken },
      body: JSON.stringify(body),
    })
    
    if (res) {
      if (res.status == 200) {
        return res.json();
      } else if (res.status == 401) {
        const data = res.json();
        console.log(data.message)
        throw ({ code: 401, msg: 'Wrong username or password' });
      } else if (res.status == 400) {
        throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
      }
    }
  } catch (err) {
    console.error(err)
  }

};

const Auth = async (username, password) => {
  const jwtData = {
    "origin": "launcher",
    "scope": "ec_auth"
  };

  try {
    const req_uuid = await this.setupUUID();
    if (req_uuid) {
      jwtData["req_uuid"] = req_uuid;
      const jwtToken = jwt.sign(jwtData, 'lulz');
      return await postReq(jwtToken);
    }
  } catch (err) {
    console.error(err);
  };
}

Upvotes: 0

A Rogue Otaku
A Rogue Otaku

Reputation: 923

await is not to be used with then.

let data = await this.setupUUID();

or

let data=null;
setupUUID().then(res=> data = res) 

Upvotes: 0

Related Questions