简体   繁体   中英

Javascript asynchronous assignment and callback

I'm sure there's an easy way to do this, but I'm having difficulty wrapping my mind around asynchronous calls and their flows. I'm trying to do a simple assignment statement in javascript, followed by setting a timer to perform operations on that object once it's been assigned. I have something along the lines of:

var info = getInfo();
$timeout(updateInfo(info), 5000);

However, I don't want the timeout to be executed until info is set initially. I've tried looking into using .then or some form of callback, but I haven't successfully determined how to do that. I'm unsure if having the parameter of info in the updateInfo call makes it so that I can't use callbacks in getInfo or what the correct flow is. I've read other articles and stack overflow responses, but couldn't find one dealing with asynchronous assignment and then using that as a paremter in a subsequent call.

getInfo and updateInfo are methods that return Highcharts graph config objects. Without copying over all the specific details:

getInfo: function() {
  return {
    options: {
      chart: {
        type: 'line'
      }
    }
    ...
  }
}

updateInfo: function(info) {
  // Here computations are performed on plot series data.
  info.series.push(...)
}

You should remember that although JavaScript does some asynchronous actions, yet the assignment to a variable is synchronous, which means that it occurs at the moment you requested for it, and won't go on to the next line until it's done.

If getInfo itself has the variable info in scope and updates it during the asynchronous call, then you shouldn't assign a value to it in the invocation of the function.

If I confused you, let me guess what you do there (and please provide the getInfo function for clarifying your question).

I'm pretty sure what getInfo does is an ajax call. So if you already use jQuery, you can simply use their ajax function:

function getInfo(){
    $.ajax({
      url: "/api/items"
    }).done(updateInfo);
}

function updateInfo(data){
      console.log ('Do something with', data);
}

getInfo();

See full documentation: http://api.jquery.com/jquery.ajax/

Both getInfo and updateInfo looks pretty sync to me. So there shouldn't be any synchronization problem.

The only thing I noticed is the wrong use of $timeout in your example. $timeout(updateInfo(info), 5000); this way updateInfo will be called before the timeout starts and the returned value will be passed as a parameter.

In order to call updateInfo after 5 seconds you have to use anonymous function or bind function.

$timeout(function() { updateInfo(info); }, 5000);

$timeout(updateInfo.bind(null, info), 5000);

For more info about bind .

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