簡體   English   中英

JavaScript承諾不執行.then()

[英]JavaScript Promise not executing .then()

我在JavaScript中遇到Promise問題。 我想做的是得到一個地址列表,然后為每個地址調用Geocode API來獲取經緯度,然后我將繼續將標記與熱圖一起繪制。 這是我的代碼:

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

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

我稱之為地址解析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;
    }

});
}

現在的問題是,盡管我設法從地址解析中打印出一些經緯度,但該程序只是在getBranchLatLng()處停止,甚至從未進入過addForecastMarker()。

一些返回我的地址:

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

然后,當我嘗試擴展鏈接時,我得到了:

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

關於如何使用“ INVALID_REQUEST”將這些地址解析回Promise父級的任何想法?

謝謝!

沒有在代碼中使用的所有測試數據和未聲明的變量,就無法生成工作代碼。 但是總的來說,我可以建議的是,您必須在ajax請求中添加一個catch塊,並且要記住, getBranchLatLng Promise中必須沒有沒有resolvingrejecting諾言的工作流。

假設萬一發生任何錯誤,您仍然想解決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');
}

但這不是您可以用來直接獲得最終結果的樣板代碼。 當任何承諾失敗時,您需要添加錯誤處理代碼。 為了您的幫助,我已使用type: 'error'兌現了這些承諾。 promiseKey的then塊內,您必須閱讀這些內容並進行進一步的錯誤處理,並從數組中刪除它們,然后再對其調用addForecastMarker

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM