Help with Promisse {<Pending>}

Asked

Viewed 575 times

1

Talk personal, all right? I’m doing a role that will be responsible for validating the ZIP code informed by the user. Basically in the call of an API the user will send the ZIP code on body and I need to validate if this ZIP code is valid, I did the function below:

    const axios = require('axios')

const obj = {
    infos: {
        addres: {
            cep: '04052030',
            street: 'Rua Orissanga',
            city: 'São Paulo'
        }
    }
}

async function cepCheck (request) {
    const data = await axios.get(`https://viacep.com.br/ws/${request.infos.addres.cep}/json/`)
 
    if(request.infos.addres.street != data.data.logradouro) {
        request.check = false
        return request
    }else if(request.infos.addres.city != data.data.localidade){
        request.check = false
        return request
    } else {
        request.check = true
        return request
    }

}

const teste = cepCheck(obj)

The Obj created is only for testing. In the scenario I described I need to know if the result of the check is false or true to return a answer to the user in the API, only then enter the problem, because it is a promise the return always comes as {pending} And I really don’t know how to get around that. For the API I am using express and in case it is necessary I send the API call code as well.

2 answers

2


Async functions Always Return a Promise. If the Return value of an async Function is not explicitly a Promise, it will be implicitly Wrapped in a Promise.

Taken from MDM web Docs [English] [Portuguese (from Brazil)] - on 11/08/2020

Which translated would be +/- that:
The return of a async function is always a precedent. If the value returned within the async function is not a Promise will be transformed into one, ie:

async function foo() {
   return 1
}

console.log('retorno da chamada é:', foo().constructor.name)

is the same thing as that:

function foo() {
   return Promise.resolve(1)
}

console.log('retorno da chamada é:', foo().constructor.name)


So in your case const teste is receiving a Promise.
That you could replace/do something like the example below:

/// teste.then(function(resultado){ ...
cepCheck(obj).then(function(resultado){
      console.log("Meu resultado é", resultado);
  })
  .catch(function(){
      console.log("Error");
  });
  • Great, thanks Icaro, I used this solution and it worked!

2

Its function cepCheck is an asynchronous function, so you need to wait using a await the result of it in the test variable (const test = cepCheck(obj))

To test, you can add a.log console before returning to the function cepCheck and check the desired value normally (since in the function cepCheck, you are already using await) or run an asynchronous function that will call the function internally

Ex:

async function cepCheck (request) {
    const data = await axios.get(`https://viacep.com.br/ws/${request.infos.addres.cep}/json/`)
 
    if(request.infos.addres.street != data.data.logradouro) {
        request.check = false
        return request
    }else if(request.infos.addres.city != data.data.localidade){
        request.check = false
        return request
    } else {
        request.check = true
        return request
    }

}



(async () => {
    const teste = await cepCheck(obj)
    console.log(teste)
})();

In my example I encapsulated your call into an asynchronous anonymous function that calls itself right after its creation. I used this way to be able to create an asynchronous environment without the need to create another function named as cepCheck and that can be implemented quietly in run of a script.js without mucking up your code too much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.