2

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
    });
4
  • 4
    Why are you using await and then? Commented May 4, 2019 at 17:55
  • To clarify the other comments, it makes no sense to use await and .then on the same promise. Commented May 4, 2019 at 18:05
  • Avoid awaiting a .then(…) chain. And your function does indeed not return anything! Commented May 4, 2019 at 18:28
  • Actually, the ugly error handling with .catch (instead of try/catch) is part of the problem. Commented May 4, 2019 at 18:29

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

await is not to be used with then.

let data = await this.setupUUID();

or

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

1 Comment

The second one should be avoided. Declaring data outside of the callback makes no sense.
0

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);
  };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.