Вполне естественно, что мои цепочечные вызовы POST и GET становятся медленнее? - PullRequest
0 голосов
/ 17 января 2019

Я полагаю (не совсем уверен), что мой код стал немного медленнее после объединения вызовов POST и GET и задавался вопросом, нормально ли это или есть другой более эффективный способ сделать это. Я основываю свое предположение на том факте, что маркер карты Google появляется после небольшой задержки на карте Google. Я считаю, что это потому, что я помещаю только что созданный маркер в массив маркеров: [] в конце цепочек POST и GET.

Изначально мой код выглядел так:

createMarker(event){
    axios.post('/marker', {
        userId: this.$store.state.auth.userId,
        marker: event.latLng
    }).then(response => {
        this.markers.push({ 'id': response.data.marker.id,
                            'lat': response.data.marker.lat,
                            'lng': response.data.marker.lng})
    }).catch((error) => console.log(error));
}

Обновленная версия объединяет запрос POST в GET .then() следующим образом:

        createMarker(event){
            var lat = event.latLng.lat();
            var lng = event.latLng.lng();
            const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key='

            axios.get(latLng)
            .then(response => {
                const name = response.data.results[0].address_components[5].long_name + ', '
                            + response.data.results[0].address_components[3].long_name
                console.log(response)
                axios.post('/marker', {
                    userId: this.$store.state.auth.userId,
                    marker: event.latLng,
                    name: name
                }).then(response => {
                    this.markers.push({ 'id': response.data.marker.id,
                                        'lat': response.data.marker.lat,
                                        'lng': response.data.marker.lng})
                }).catch((error) => console.log(error));
            }).catch((error) => console.log(error))
        }

Мне нужно объединить методы в цепочку, потому что я хочу использовать giocode api от google, чтобы получить название города на основе значений lat и lng, а затем передать его в мой запрос POST, чтобы я мог сохранить его в своей собственной базе данных.

Ответы [ 2 ]

0 голосов
/ 17 января 2019

Если id не требуется для отображения маркера на карте, попробуйте следующее:

Добавьте маркер с пустым id перед вызовами GET / POST. Таким образом, не должно быть никаких задержек.

И обновите значение id после завершения вызовов POST.

Проверьте комментарии в коде

createMarker(event){
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key='

    // add the marker to the map first
    this.markers.push({ 'id':  '',
                        'lat': lat,
                        'lng': lng})
    // save the position of the marker, so we can add `id` later
    var index = this.markers.length - 1;

    axios.get(latLng)
        .then(response => {
            const name = response.data.results[0].address_components[5].long_name + ', '
                       + response.data.results[0].address_components[3].long_name

            console.log(response)
            axios.post('/marker', {
                userId: this.$store.state.auth.userId,
                marker: event.latLng,
                name: name
            }).then(response => {
                // update marker index
                this.markers[index].id = response
            }).catch((error) => console.log(error));
        }).catch((error) => console.log(error))
0 голосов
/ 17 января 2019

Да, вы правы. Окончательный результат - задержка двух сетевых запросов. Однако вы не правильно используете цепочку обещаний. Это похоже на ад обратного вызова. Вы можете написать это более элегантно, например:

createMarker(event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();

    const latLng = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=';

    const userId = this.$store.state.auth.userId;

    axios.get(latLng)
        .then((response) => response.data.results[0])
        .then((x) => `${x.address_components[5].long_name},${x.address_components[3].long_name}`)
        .then((name) => axios.post('/marker', {
            name, userId
            marker: event.latLng,
        }))
        .then((response) => this.markers.push({ 
            id: response.data.marker.id,
            lat: response.data.marker.lat,
            lng: response.data.marker.lng
        }))
        .catch((error) => console.log(error));
}

Обещания помогают сгладить вложенные асинхронные вызовы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...