简体   繁体   English

JavaScript承诺不执行.then()

[英]JavaScript Promise not executing .then()

I was having some problem with Promise in JavaScript. 我在JavaScript中遇到Promise问题。 What I am trying to do is I got a list of address, then for each address, I need to call the geocode API to get the lat lng, then I will proceed to plot the markers together with the heatmap. 我想做的是得到一个地址列表,然后为每个地址调用Geocode API来获取经纬度,然后我将继续将标记与热图一起绘制。 Here is my code: 这是我的代码:

let promiseKey = Promise.all(
          result.map()
        );

        var addedMarkers = promiseKey.then(
        markers => Promise.all(
          markers.map()
        )
        )
        .then(drawForecastHeatmap);

The part where I call the geocode API: 我称之为地址解析API的部分:

function getBranchLatLng(address, branchName, total, queKey){
return new Promise(function(resolve){
    var key = jQuery.rand(geoCodKeys);
    var url = 'https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address='+address+'&sensor=false';

    $.ajaxq (qyName, {
        url: url,
        dataType: 'json'
    }).done(function( data ) {
        var address = getParameterByName('address', this.url);
        var index = errorArray.indexOf(address);
        try{
            var p = data.results[0].geometry.location;
            var latlng = new google.maps.LatLng(p.lat, p.lng);

            var markerItem =
                {
                    'lat': p.lat,
                    'lng': p.lng,
                    'address': address,
                    'branchName': branchName,
                    'total': total,
                };
            console.log(markerItem);
            resolve(markerItem);

            if (index > -1) {
                errorArray.splice(index, 1);
            }
        }catch(e){
            if(data.status = 'ZERO_RESULTS')
                return false;

            //on error call add marker function for same address and keep in Error ajax queue
            getBranchLatLng( address, 'Error' );
            if (index == -1) {
                errorArray.push( address );
            }
        }
    });

    //mentain ajax queue set
    queuCounter++;
    if( queuCounter == setLimit ){
        queuCounter = 0;
    }

});
}

The problem now is, the program just stopped at getBranchLatLng() and never even go into the addForecastMarker() although I managed to print out some lat lng from geocode. 现在的问题是,尽管我设法从地址解析中打印出一些经纬度,但该程序只是在getBranchLatLng()处停止,甚至从未进入过addForecastMarker()。

Some of the address returning me: 一些返回我的地址:

jquery.min.js:4 GET https://maps.googleapis.com/maps/api/geocode/json?key=&address= 400 ()

Then when I try to extend the link, I am getting this: 然后,当我尝试扩展链接时,我得到了:

error_message: "Invalid request. Missing the 'address', 'bounds', 'components', 'latlng' or 'place_id' parameter."
results :[]
status: "INVALID_REQUEST"

Any ideas on how to resolve those address with 'INVALID_REQUEST' back to the Promise parent? 关于如何使用“ INVALID_REQUEST”将这些地址解析回Promise父级的任何想法?

Thanks! 谢谢!

It is not possible to generate the working code without having all the test data and undeclared variable that you are using in your code. 没有在代码中使用的所有测试数据和未声明的变量,就无法生成工作代码。 But overall what I can suggest is that, you must add a catch block to the ajax request, and keep into mind that there must be no workflow in your getBranchLatLng Promise that is not resolving or rejecting the promise. 但是总的来说,我可以建议的是,您必须在ajax请求中添加一个catch块,并且要记住, getBranchLatLng Promise中必须没有没有resolvingrejecting诺言的工作流。

Assuming that, incase of any error, you still want to resolve your getBranchLatLng , I have updated your code like this, so that there are no workflow in your getBranchLatLng promise that won't resolve or reject 假设万一发生任何错误,您仍然想解决getBranchLatLng ,我已经像这样更新了您的代码,以便您的getBranchLatLng承诺中没有不会resolvereject工作流程

let promiseKey = Promise.all(
          result.map(el=>getBranchLatLng(el.branchAddress, el.branchName, el.amount))
        );

        var addedMarkers = promiseKey.then(
        markers => Promise.all(
          markers.map(marker => addForecastMarker(marker))
        )
        )
        .then(drawForecastHeatmap)
        .catch(functon(e) {
            //Do the error handling here
        });

function getBranchLatLng(address, branchName, total, queKey) {
return new Promise(function(resolve, reject) {
    var key = jQuery.rand(geoCodKeys);
    var url = 'https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&address='+address+'&sensor=false';

    var qyName = '';
    if( queKey ) {
        qyName = queKey;
    } else {
        qyName = 'MyQueue'+queuCounter;
    }

    $.ajaxq (qyName, {
        url: url,
        dataType: 'json'
    }).done(function( data ) {
        var address = getParameterByName('address', this.url);
        var index = errorArray.indexOf(address);
        try{
            var p = data.results[0].geometry.location;
            var latlng = new google.maps.LatLng(p.lat, p.lng);

            var markerItem =
                {
                    'lat': p.lat,
                    'lng': p.lng,
                    'address': address,
                    'branchName': branchName,
                    'total': total,
                };
            console.log(markerItem);
            if (index > -1) {
                errorArray.splice(index, 1);
            }
            resolve(markerItem);

        }catch(e) {
                if (index == -1) {
                errorArray.push( address );
            }
                resolve({type: 'error', status: data.status});

        }
    })
    .catch(function(e) {
        resolve({type: 'error', status: data.status});
      //Instead of resolving with error code you can also reject the promise
      //reject(e);
    });

    //mentain ajax queue set
    queuCounter++;
    if( queuCounter == setLimit ){
        queuCounter = 0;
    }

  }
)};

function addForecastMarker(marker) {
console.log('adddddd markerssssss');
}

But this is not the Boilerplate code that you can use to directly get the final result. 但这不是您可以用来直接获得最终结果的样板代码。 You need to add the error handling code when the any of the promise would fail. 当任何承诺失败时,您需要添加错误处理代码。 For your help, I have resolved those promises with type: 'error' . 为了您的帮助,我已使用type: 'error'兑现了这些承诺。 Inside the then block of promiseKey you must read those and do further error handling and remove those from the array before calling addForecastMarker over it. promiseKey的then块内,您必须阅读这些内容并进行进一步的错误处理,并从数组中删除它们,然后再对其调用addForecastMarker

Hope that it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM