Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 29622

React Native get value from promises after fetch data finished

$
0
0

I'm trying to get value from another function that call fetch promises but it returned undefined, i think the problem is the result wouldn't wait the process from called function until it done.

Here is the code:

var myConnection = require('../components/connection');var RequestToken = React.createClass({getInitialState: function() {    return {    };},componentDidMount: function(){    AsyncStorage.getItem('token').then((value) => {        if(typeof value != null){            this.setState({"token": value});            // call this function            this.catchToken(value);        }    }).done();},catchToken: async function(token){    try{        var URL = "http://someurl.com/";        var params = {            token:token        }        let val = await myConnection.now(URL,params);            this.setState({               responseAPI:val            });            // returned undefined            console.error(this.state.responseAPI);    }catch (e){        console.error(e);    }}});

and connection.js

function timeout(ms, promise) {return new Promise(function(resolve, reject) {    setTimeout(function() {        reject(new Error("Connection timeout"))    }, ms);    promise.then(resolve, reject);});}var myConnection = {now: async function(URL,params){    //return "OK";    var formData = new FormData();    for (var k in params) {        formData.append(k, params[k]);    }    timeout(10000, fetch( URL, {        method: 'POST',        headers: {'Accept': 'application/json','Content-Type': 'multipart/form-data'        },        body: formData    })).then(        (response) => response.json()    ).then((res) => {        // result data        return res;    }).catch((error) => {        console.error(error);    }).done();}};module.exports = myConnection;

Can someone explain how to get returned value after function process is done?

Thanks


Viewing all articles
Browse latest Browse all 29622

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>