简体   繁体   中英

How to make a javascript callback function execute first?

I have the following code (that I have stripped and simplified):

function myOrder() {
        setLocation(); // sets a value for global variable 'location'  
                       // using GET         

        $.post('http://111.111.111.111/order', {
                Item: Chair,
                Price: 50, 
                Location: location;
                                               })
}

The problem is that this function executes the post() code before the setLocation() callback function has finished.

I need the setLocation() function to finish first, so it can assign a global variable for 'location', which is then used as a value in the POST part.

Does anyone know if this can be done?

Thanks

EDIT: To clarify: setLocation() is a GET request, that gets the current location via GPS and stores it under a global variable name 'location'.

So what I think is happening is that the myOrder() method POSTS before the callback function has finished its GET response.

Use async flow

function setLocation() {
  return new Promise((resolve, reject) => {
    // I do my stuff

    // I finished
    resolve();
  });
}

function myOrder() {
        setLocation().then(() => {
          $.post('http://111.111.111.111/order', {
                  Item: Chair,
                  Price: 50, 
                  Location: location;
                                                 })        
        })
}

As you did not provide the implementation of setLocation , I'll assume you use $.get or some similar jQuery function ( $.ajax , $.getJSON , ...).

In that case, do not use the callback function of $.get , and do not store the response data a global variable, but return $.get(...) because it is a promise:

function setLocation() {
    // Return the promise object returned by $.get, $.getJSON, $.ajax, ...
    //  instead of using the callback function, and don't store the result
    //  in a global variable
    return $.get("myurl").then(function (data) {
        // As you did not provide the code, this serves only as example. The 
        // way you extract the latitude and longitude from the response may be
        // different. Adapt as needed:
        data = JSON.parse(data);
        var lat = data.result[0].lat;
        var lng = data.result[0].lng;
        // Return value will be the promised value: adapt the format as needed,
        // This will become the location variable content in your other function 
        return { lat, lng }; 
    });
}
function myOrder() {
    // Use the `then` method on the jQuery promise, and return
    //   the result of the `then` method again, so you can chain
    //   on myOrder() as well...
    return setLocation().then(function (location) {
        // Return the `$.post` result:
        return $.post('http://111.111.111.111/order', {
            Item: Chair,
            Price: 50, 
            Location: location;
       });
    });
}

If the setLocation function is an asynchronous function, you will need to change it to receive a callback function after it completes.

function myOrder() {
   setLocation(function() {
      $.post('http://111.111.111.111/order', {
            Item: Chair,
            Price: 50, 
            Location: location
      });
   });
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM