Javascript 数组返回了元素,但是当记录长度时我得到零

标签 javascript react-native

尝试使用异步函数从 API 获取值。我需要能够立即访问数组中的值。

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)
}

这是当我查看记录器时出现的问题,我得到一个长度为二十一的数组,但是当记录长度本身时它显示为零。 enter image description here

最佳答案

如果您使用async wait,则不必使用then()。你能做的是

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

希望这有效

关于Javascript 数组返回了元素,但是当记录长度时我得到零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637216/

相关文章:

javascript - 识别 iframe 上的操作

react-native - 如何使用 expo 实现带有 react-native 的 strip ?

ios - defaultNavigationOptions 中的默认背景颜色

javascript - 当用户从 React Native 中的另一个页面导航回页面时,如何重新加载页面?

javascript - 为每个td添加事件监听器

javascript - 使用javascript变量设置元素高度

javascript - 嵌入缩略图 Youtube 视频

javascript - 错误 : Cannot find module 'vue-loader-v16/package.json'

javascript - 如何使用 Expo 在 React-Native 应用程序上顺序运行异步函数

firebase - 在 React Native 中使用 Firebase 云功能的博览会推送通知