mardi 4 octobre 2016

Is there a well known design pattern to allow callbacks to be registered after the async call?

When you make an async call you usually have to pass it a callback to process the result.

This is counter-intuitive to the one reading the code. We usually think about what to do and then about what to do later but in this cases we need to define what to do with the result before we define the action that is run first.

Example:

$.ajax({
    url : url1,
    success: function(data) {
        data1 = data;
        if(data2) perform();
    },
});

I have seen (and I implemented myself in java) other pattern where you make the async call first getting a token for the operation and then you register callbacks to it.

If the async operation has been run before the callback register then it (the callback) is called synchronously of it it hasn't been run it works as a normal callback like a subscription to the result then it is run.

Example (pseudocode):

ajax(url)
  .andThen({ successHandler code })
  .onError({ errorHandler code})

What is the name of this pattern?

Aucun commentaire:

Enregistrer un commentaire