解決非同步使用Javascript callback() 回調函數

5 月 21, 2018 | | 0 條留言

callback()

回調函數是一個作為參數傳遞給另一個函數的函數,然後在外部函數中調用該函數來完成某種例程或動作。

callback()簡單的例子:

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

上面的例子是一個同步回調,因為它立即執行。

但請注意,回調通常用於在異步操作完成後繼續執行代碼- 這些稱為異步回調。例如,我們簡單的maps-example.html示例(也可以參考它)使用Google地圖API和地理定位API來顯示設備當前位置的地圖。

因為從GPS獲取設備的坐標是異步的(我們不知道數據何時會被返回),該Geolocation.getCurrentPosition()方法將一個匿名回調函數作為參數,它本身將返回的坐標數據作為參數。該函數僅在返回坐標數據時執行。

另一個範例Ajax

如何使用Ajax axios 非同步返回資料

var registerUser=function(data, callback){
  axios.post('http://localhost:8080/register',{
    phone:data.phone,
    password:data.password,
    email:data.email
  }).then(response =>{
    callback(response.data.message);
    console.log(response.data.message);
  }).catch(err =>{
    console.log(err);
  })
}

registerUser(data, function(response) {
  console.log(response)
});