2016-08-31 131 views
0

如何爲數組返回數據而不是函數onSuccessonError?什麼,我需要將數據傳遞給數組javascript

function onSuccess(position) { 
    alert('Latitude: '   + position.coords.latitude   + '\n' + 
      'Longitude: '   + position.coords.longitude   + '\n' + 
      'Altitude: '   + position.coords.altitude   + '\n' + 
      'Accuracy: '   + position.coords.accuracy   + '\n' + 
      'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + 
      'Heading: '   + position.coords.heading   + '\n' + 
      'Speed: '    + position.coords.speed    + '\n' + 
      'Timestamp: '   + position.timestamp    + '\n'); 
} 
function onError(error) { 
    alert('code: ' + error.code + '\n' + 
      'message: ' + error.message + '\n'); 
} 
navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 }); 

例子:

geolocation = navigator.geolocation.watchPosition(null, null, { timeout: 30000 }); 
if(!geolocation.error) 
     alert(geolocation.coords.latitude); 

插件:https://github.com/apache/cordova-plugin-geolocation

+0

可能重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-異步調用) – vlaz

+0

我沒有發現我的案例。你能解釋我嗎? –

+0

沒有例子。這是解釋說,JavaScript不工作的方式,你問。你需要從一個異步的思維集中來解決它。 – adrianj98

回答

0

我從你的問題,你想你的代碼執行線性猜測。但它不能。代碼塊被執行,然後,最終,該位置到達並且調用回調。但它發生在不同的時間(甚至幾毫秒)和不同的堆棧跟蹤。這就是異步JavaScript的工作原理。

如果你不熟悉這個概念,你應該閱讀一些關於這個主題的文章。爲了供您參考,我已將您的代碼轉換爲Promise代碼,這是可用於幫助解決異步問題的最佳技術之一。

new Promise(function(resolve, reject) { 
    navigator.geolocation.watchPosition(resolve, reject, { timeout: 30000 }); 
}) 
.then(function(location) { 
    console.log(location.coords.latitude); 
}) 
.catch(function (error) { 
    console.log('code: ' + error.code + '\n' + 
     'message: ' + error.message + '\n'); 
}); 

順便說一句,請幫個忙,使用console.logalert()是2000年的! :)