【问题标题】:React native async/await do not work, strange behavior反应本机异步/等待不起作用,奇怪的行为
【发布时间】:2018-09-21 16:03:50
【问题描述】:

我有函数 CalcDistanceBetweenGoogle,它进行获取,传递坐标“to”和“from”,应该返回两个坐标之间的距离。

如果距离小于 20000(20 公里),则将其插入到数组中。

但不能正常工作,稍后打印。

我做错了什么?

博览会示例:https://snack.expo.io/H1NianjoG

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';

export default class App extends Component {
  state = {};

  componentDidMount() {
    this.calc();
  }

  calc() {
    var markers = [
      {
        id: '269849444',
        name: 'Ziano Piacentino',
        lat: 45,
        lng: 9.4,
      },
      {
        id: '649296407',
        name: 'Monte Bondone',
        lat: 46.0315,
        lng: 11.05685,
      },
      {
        id: '300151628',
        name: 'Cima Calisio',
        lat: 46.0977158258,
        lng: 11.1443512052,
      },
      {
        id: '266239592',
        name: 'Trient, Trentino-Alto Adige, Italy',
        lat: 46.0667,
        lng: 11.1333,
      },
      {
        id: '130313194355778',
        name: 'Monte Celva',
        lat: 46.0695882,
        lng: 11.1783065,
      },
      {
        id: '217942785',
        name: 'Trento, Italy',
        lat: 46.0667,
        lng: 11.1333,
      },
      {
        id: '478657266',
        name: 'Mercatino di Natale a Levico Terme città da amare',
        lat: 46.0099217576,
        lng: 11.3052625593,
      },
      {
        id: '288554028181059',
        name: 'Fontana Del Nettuno, Trento',
        lat: 46.0675553413,
        lng: 11.1213752236,
      },
      {
        id: '252747884',
        name: 'Duomo di Milano - Milan Cathedral',
        lat: 45.4646680426,
        lng: 9.1904055604,
      },
      {
        id: '213183830',
        name: 'Piacenza',
        lat: 45.0167,
        lng: 9.66667,
      },
      {
        id: '213183830',
        name: 'Home',
        lat: 45.0167,
        lng: 9.66667,
      },
    ];

    var group = [];
    for (var i = 0; i < markers.length; i++) {
      var array = [];
      for (var j = 0; j < markers.length; j++) {
        if (i != j) {
          var ci = markers[i];
          var cj = markers[j];
          this.CalcDistanceBetweenGoogle(ci, cj).then(async el => {
            if (el.dist <= 20000) {
              console.log(el)
              array.push(el.to);
            }
          });
        }
      }
      group.push(array);
    }
    console.log(group);
  }

  async CalcDistanceBetweenGoogle(from, to) {
    var lat1 = from.lat, lon1 = from.lng, lat2 = to.lat, lon2 = to.lng;
    try {
      const response = await fetch(
        'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' +
          lat1 +
          ',' +
          lon1 +
          '&destinations=' +
          lat2 +
          ',' +
          lon2 +
          '&mode=driving&language=it-IT',
        {
          method: 'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        }
      );
      const json = await response.json();
      return {
        from: from,
        to: to,
        dist: json.rows[0].elements[0].distance.value,
      };
    } catch (error) {
      console.error(error);
    }
  }

  render() {
    return <View style={styles.container} />;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 80,
    backgroundColor: '#ecf0f1',
  },
});

【问题讨论】:

    标签: javascript reactjs react-native async-await fetch


    【解决方案1】:

    首先,将calc 声明为async

    async calc()
    

    然后在嵌套循环中,在调用CalcDistanceBetweenGoogle 时,使用await 等待响应。

    const el = await this.CalcDistanceBetweenGoogle(ci, cj);
    if (el.dist <= 20000) {
        console.log(el);
        array.push(el.to);
    }
    

    我只做了这些更改,group 数组填充了值,尽管很少有索引是空白的。

    【讨论】:

    • 谢谢,最后一件事。我在 forEach 中有相同的调用,但它似乎不起作用,我做了这样的事情:a.forEach (async or => {const el = await this.CalcDistanceBetweenGoogle (center, o); ...}) ;我做错了什么?
    • 不看就很难判断错误的陈述。如果您可以共享您的代码,它可能会有所帮助。顺便说一句,如果上面的语句是你写的,那么你在调用this.CalcDistanceBetweenGoogle时犯了拼写错误,你把o而不是or
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2018-07-18
    • 2021-11-14
    • 1970-01-01
    • 2023-02-21
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多