2017-12-17 27 views
1

JavaScript의 Promise에 문제가 있습니다. 내가하려고하는 일은 주소 목록을 얻은 다음 각 주소에 대해 지오 코드 API를 호출하여 위도 lng을 얻은 다음 히트 맵과 함께 마커를 플롯하기 위해 진행할 것입니다.JavaScript 약속 실행 안 함 .then()

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로 이동) 여기 내 코드입니다 내가 지리 코드에서 약간의 lat를 프린트 할 수는 있었지만.

주소의 일부는 나를 돌아 : 내가 링크를 확장하려고 할 때 다음

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와 그 주소를 해결하는 방법에 대한 아이디어 약속의 부모에게 돌아가는거야?

감사합니다.

+3

getBranchLatLng mybe에서 거부를 사용하지 마십시오. 오류가 발생하여 약속이 중지되는 이유 –

+0

@AmitWagner 해당 덩어리를 catch()하는 것을 의미합니까? – hyperfkcb

+0

아약스 함수에서 오류가있을 수 있습니다. 항상 코드를 작성했는지 확인하기 위해 allways를 시도해 보시고 reject를 사용하여 promise chain –

답변

0

코드에서 사용중인 모든 테스트 데이터 및 선언되지 않은 변수를 사용하지 않고도 작업 코드를 생성 할 수 없습니다. 그러나 제안 할 수있는 전반적인 내용은 Ajax 요청에 catch 블록을 추가해야하고 resolving 또는 rejecting이 아닌 워크 플로가 getBranchLatLng Promise에 없어야한다는 것입니다. 당신의 getBranchLatLng 약속에는 워크 플로우이 없도록 오류의 넣다, 여전히 getBranchLatLng를 해결하고자하는 것으로 가정

, 나는이 같은 코드를 업데이트 한 것을하지 않습니다 resolve 또는 reject

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의 블록 안에 그 이상을 읽고 그 위에 addForecastMarker를 호출하기 전에 배열에서 제거해야합니다.

도움이 되길 바랍니다.

+0

내가 본 것을 알았어! 정말 고마워! 나는 그럭저럭 일할 수 있었다. 몇 번 더 테스트 해 보겠습니다. – hyperfkcb

+0

좋아요! 도와 줘서 다행 :) –