如何使initMap()函数在执行之间等待

How to make function initMap() wait in between its execution?

本文关键字:执行 之间 等待 函数 何使 initMap      更新时间:2023-09-26

我有两个函数

function otherfun(val){
    var data = {'latitude': val[0], 'longitude': val[1]};
    $.post(URL, data, function(response){
        if(response){ 
           // I want to return response from here
        }
        else{ alert('Error! :('); }
    });
}

function initMap() {
      var pos = {};
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var output = otherfun([pos.lat,pos.lng]);
        alert(output);
        // use output's value further
}

函数initMap()初始执行。我将lat和lng的值传递给otherfun()

我想:

  1. 返回函数otherfun的响应值
  2. 使initMap()函数等待otherfun()返回并存储在变量输出
  3. 然后显示带有输出值的警告框。

将initMap拆分为两个函数。初始init和otherfun后调用的回调函数

function otherfun(val) {
    var data = {'latitude': val[0], 'longitude': val[1]};
    $.post(URL, data, function(response){
        if(response){ 
           otherfunCallback(response);    // Call a callback function
        }
        else{ alert('Error! :('); }
    });
}
function initMap() {
      var pos = {};
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        otherfun([pos.lat,pos.lng]);
}
// The callback function that alert for the output
function otherfunCallback(data) {
    // ... extract the data you need
    var output = ...;
    alert(output);   
}

如果您需要存储输出结果,您可以将其保存在一个变量中,而不是区域设置。