React Native - fetch (url) always returning a Promise

1

I'm starting in React Native, I had no problems until I started doing HTTP requests. I'm using this function:

async getJSON(url, parameters){
    try{
        //check if URL isn't empty
        if(url.length == 0)
            return false;

        //construct HTTP parameters
        var params = '';
        for (var key in parameters) {
            if(params.length)
                params += "&";

            params += key + "=" + encodeURIComponent(parameters[key]);
        }
        //doing request
        const response = await fetch('${url}${params}');
        let body = await response.json();

        return body;
    }catch(err){
        console.error(err);
        return false;
    }
}

So I got Promisse to follow:

Promise {_40: 1, _65: 0, _55: null, _72: Handler}
v
_40:1
_55:{success: false, msg: "segredo não informado"}
_65:1
_72:null
__proto__:Object

This JSON in object _55 is what I want to get, could simply access and get it, but that would not be correct (it goes that number changes, haha).

So I adapted the code below from from that post , and entered the code before the return body; of the first code.

Promise.resolve(body).then(function(value) {
    console.log(value); //aqui deu log do JSON!
    body = value; // essa atribuição não funcionou, por algum motivo
});

The above assignment should pass the JSON to the body , but in the end returned the Promise again ... I tried putting a await before Promise.resolve but nothing changed .

I looked at the documentation , I will search then-> gt; then schema. I do not know what else to do.

    
asked by anonymous 18.06.2018 / 03:50

1 answer

0

Since Promise.resolve is asynchronous, inside an asynchronous function, I solved the problem by putting it in the main class. It works like this:

In the main class, I call the method that returns the JSON of a webservice:

let result = conn.getJSON(this, url.login, params);
  

Note: The getJSON method remains the same as the first question code.

The Promise object will be in result , then just below it I will do the JSON handling.

if(result){
     Promise.resolve(result).then(function(json) {
       //login successfully
       if(json.success){
         console.warn("loging in...");
       }else{
         console.warn("wrong login");
       }

     });
   }else{
     Alert.alert(
       'Erro LOG-2',
       'Nenhuma informação retornada do servidor. Talvez uma instabilidade na rede tenha causado isso. Tente novamente.',
            [
         {text: 'OK, vou verificar.', onPress: () => console.log('OK Pressed')},
            ],
       { cancelable: true }
      )
   }
    
18.06.2018 / 05:42