2017-08-21 28 views
0

我正在嘗試Google地圖API功能,但似乎沒有成功。調用我的函數時,我得到Cannot read property 'then' of undefined如何通過goole.maps.places API getPlacePredictions promisify回調?

我試圖按照該線程中的例子,但沒有運氣:Turn callback into promise

回調函數應該是這樣的:

predictionService = new google.maps.places.AutocompleteService(); 
predictionService.getPlacePredictions(
    { input: '1 main street, south bend' }, 
    displayPredictionSuggestionsCallback 
); 

function displayPredictionSuggestionsCallback(input){ 
    // output results 
} 

我promisifaction看起來是這樣的:

predictionService = new google.maps.places.AutocompleteService(); 

function getPredictionSuggestion (input){ 

    var dfd = $.Deferred(); 

    predictionService.getPlacePredictions({ 
     input: input 
    }, function (place, status) { 
     if (status != google.maps.places.PlacesServiceStatus.OK) { 
      return dfd.reject("Request failed: " + status); 
     } 
     dfd.resolve(place).promise(); 
    }); 
} 

這是調用服務的功能:

getPredictionSuggestion('1 main street, south bend').then(function(results) { 
     console.log('promise results = ' + results); 
    }, function(err) { 
     alert(err); 
    }); 

回答

2

你正在做的事情是正確的。改變的事情:

  1. 您需要從您的功能返回承諾。在末尾添加return dfd.promise();

  2. 不需要需要return在您的回調中,只需else。請致電。

所以:

predictionService = new google.maps.places.AutocompleteService(); 

function getPredictionSuggestion (input){ 

    var dfd = $.Deferred(); 

    predictionService.getPlacePredictions({ 
     input: input 
    }, function (place, status) { 
     if (status != google.maps.places.PlacesServiceStatus.OK) { 
      dfd.reject("Request failed: " + status); // *** 
     } else {          // *** 
      dfd.resolve(place);     // *** 
     }           // *** 
    }); 

    return dfd.promise();       // *** 
} 

這對jQuery的Deferred。你可能會想,如果需要使用本地Promise代替,用填充工具:

predictionService = new google.maps.places.AutocompleteService(); 

function getPredictionSuggestion(input) { 
    return new Promise(function(resolve, reject) { 
     predictionService.getPlacePredictions({ 
      input: input 
     }, function (place, status) { 
      if (status != google.maps.places.PlacesServiceStatus.OK) { 
       reject(new Error(status)); 
      } else { 
       resolve(place); 
      } 
     }); 
    }); 
} 

注意使用new Errorreject。通常,將Error與拒絕一起使用非常有用,因爲它提供了上下文(出現「錯誤」的位置)。