-3
const axios = require('axios');

const RequestLogin = async function () {

    let auth = {
        "user_name": "username12l",
        "password": "password12l",
    };

    let res = await axios.post('https://.../api/v1/login', auth);
    //console.log("Dentro da Funcao", res);
    return await res;
}
const login = RequestLogin()

console.log("loginSysaidCookie -> ", RequestLogin)
console.log("Login -> ", login)

How do I send the data to the const login?

My console --->

loginSysaidCookie -> [AsyncFunction: loginSysaidCookie]
login -> Promise { <pedings> }

I want the constant login to get the RequestLogin response.

  • 3
    Does this answer your question? [Why is my asynchronous function returning Promise { } instead of a value?](https://stackoverflow.com/questions/38884522/why-is-my-asynchronous-function-returning-promise-pending-instead-of-a-val) – jonrsharpe Dec 20 '22 at 13:29

1 Answers1

0

Using the await keyword

Like this:

const login = await RequestLogin();

Explanation: Because the function is asynchronous, it allows other processes to run even if it's not finished running. You can add the await keyword to tell javascript to wait for the function to finish running before continuing on.

Catch: Can't be used on the top level (only in functions, etc)

Using .then() and .catch()

Using .then() and .catch() allow for top-level use. .then() must be added following the function and then you can add a function in the .then() which will run what you want to run after the main function runs. .catch() also allows a function as an argument which runs when an error is returned.

Example:

async function fetchFromDatabase() {
    ...
}

fetchFromDatabase.then((res) => {
    console.log(res)
}).catch((error) => {
    console.log("Error: ", error)
})
incog
  • 101
  • 3
  • 1
    const login = await RequestLogin() ^^^^^ SyntaxError: await is only valid in async functions and the top level bodies of modules – Edson Luiz dos Santos Junior Dec 20 '22 at 13:38
  • You can also use .then().catch() instead of await, but I find await much cleaner for most situations. – incog Dec 20 '22 at 13:39
  • @EdsonLuizdosSantosJunior You also must have the function in an async function. Then you can call that function at the top level. I think you can use .then().catch() on the top level though. – incog Dec 20 '22 at 13:40
  • @EdsonLuizdosSantosJunior I edited my answer to be more thorough, hopefully, it helps! – incog Dec 20 '22 at 13:51
  • thanks for your help but do you know how can get the res or err and send it to a variable? – Edson Luiz dos Santos Junior Dec 20 '22 at 14:05
  • @EdsonLuizdosSantosJunior You can initialize the variable with let (maybe have a default value like undefined or something) and then change the variable once fetched. You can even have all future code inside the .then() function. – incog Dec 20 '22 at 14:12