2015-12-31 9 views
5

Sto usando l'API fetch con React Native.Perché il recupero restituisce un hash strano di numeri interi?

La mia risposta segue un formato normale di {"message": "error here"} se lo stato è> = 400, che mostrerò in un popup nativo.

Sto cercando di chiamare response.json() dopo aver rilevato un guasto, ma mantiene mettere tutto in un formato strano ...

{ _45: 0, _81: 0, _65: null, _54: null }

Per qualsiasi motivo ... la risposta effettiva voglio si trova in _65 ... Non ho idea di cosa siano queste chiavi casuali.

Quindi attualmente devo accedervi tramite _bodyText, ma presumo che sia sbagliato perché è un metodo di sottolineatura privato.

Cosa sto sbagliando?

var API = (function() { 

    var base = 'https://example.com/api/v1'; 

    var defaults = { 
    credentials: 'same-origin', 
    headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    } 
    }; 

    var alertFailure = function(response) { 
    if (response.status >= 200 && response.status < 400) { 
     return response; 
    } else { 
     var json = JSON.parse(response._bodyText || '{}'); 
     var message = json.message || 'There was a problem. Close the app, and try again later.'; 

     var error = new Error(message); 
     error.response = response; 
     throw error; 
    } 
    }; 

    var callAPI = function(url, opts) { 
    opts.headers['X-Version'] = 'v' + Package.version; 

    return fetch(base + url, opts) 
     .then(alertFailure) 
     .then((response) => { 
     return response.json(); 
     }) 
     .catch((error) => { 
     Alert.alert(null, error.message); 
     }); 
    }; 

    return { 

    get: function(url, opts) { 
     var fullOpts = Object.assign({}, defaults, opts); 
     return callAPI(url, fullOpts); 
    }, 

    post: function(url, data, opts) { 
     var fullOpts = Object.assign({}, defaults, { 
     method: 'POST', 
     body: JSON.stringify(data || {}) 
     }, opts); 
     return callAPI(url, fullOpts); 
    } 
    }; 

})(); 

risposta

8

La risposta è che .json() restituisce una promessa ... quindi ho dovuto fare tutto da dentro .then()

+0

Questo è anche lo stesso per 'asyncstorage' – James111

+0

Si è verificato lo stesso problema con' async' e 'await'. Sto ancora cercando di risolverlo. – Dan

+0

Ho aggiunto il mio problema qui http://stackoverflow.com/questions/36285564/why-does-fetch-return-a-weird-hash-of-integers-part-2 – Dan

1

AsyncStorage.getItems restituisce sempre una promessa. È possibile utilizzare questo metodo al di sotto

AsyncStorage.getItem("access_key").then((value)=> 
       { 
        console.log(value); 
       }); 
1

ti consiglierei di utilizzare la nuova sintassi ES7 async/await, sono più facili da capire che usare .then()

Per usarlo, basta dichiarare un metodo con il prefisso async e al suo interno aspettate di aspettare che la chiamata finisca.

es

async someMethod(){ 
    result = await fetch(URL); // Do some request to any API. 
    // Use the result after that knowing that you'll have it completed. 
} 

Spero che questo aiuta, almeno a mio parere, trovo questo più facile che usare .then(), in particolare quando si ha a che fare più chiamate all'interno dello stesso metodo.

Problemi correlati