mayankmehtani
mayankmehtani

Reputation: 435

Javascript array returned with elements but when logging length I get zero

Trying to get values from an API using async functions. I need to be able to access the values in the array immediately.

componentDidMount() {
    var devices = this.props.navigation.state.params.userInfoState.deviceIds

    async function call_vstat(device, token)  {
        try {
          let response = await fetch(
            'http://app.yatis.io/api/admin/getDeviceStatus?api_access_token=' + token + '&deviceId=' + device,
          );
          let responseJson = await response.json();
          return responseJson;
        } catch (error) {
          console.error(error);
        }
    }


    var results = []
    for (i = 0; i < devices.length; i++) {
        var result = call_vstat(devices[i], my_token)
        .then( (result) => (results.push(result) ) )
    }

    console.log(results.length)
    console.log(results)
}

Here's the issue when I look at the logger, I get an array of length twenty one but when logging the length itself it shows zero.enter image description here

Upvotes: 0

Views: 548

Answers (2)

sibasishm
sibasishm

Reputation: 442

As mentioned in my comments,

    var promiseArray = [];
    for (i = 0; i < devices.length; i++) {
        promiseArray.push(call_vstat(devices[i], my_token));
    }

    var results = await Promise.all(promiseArray);

    if (results.length > 0) {
        //perform your business logic after this check to avoid any errors
    }

Upvotes: 0

Karthik
Karthik

Reputation: 1442

If you are using async await you don't have to use the then(). What you can do is

for (i = 0; i < devices.length; i++) {
    var result = await call_vstat(devices[i], my_token)
    results.push(result) 
}

Hope this works

Upvotes: 1

Related Questions