Search code examples
javascriptasynchronouses6-promise

Using promises when response callback


I'm trying to figure out how to use promises in a test I'm writing. I'm using plain ol' native promises in the browser. No libraries (yet)

The test requires communicating asynchronously with a server, where I get the server response via a callback

I have a server object where I register the callback like so:

server.onresponse = function(data){
  //do stuff with data
}

The test requires sending a series of commands to the server that change based on the servers response. I send the commands to the server like so

server.sendCommand({data:"do something"})

Based on the command, the server would raise the onresponse callback. I would need to read the data that the server sent to decide what the next command should be.

The interaction should be something like

  • send command 1 and wait
  • process data from onresponse callback
  • send command 2 and wait
  • process data from onresponse callback

I would like to use promises to make this interaction read a bit clearer. Like something like a series of .then()s .

I realize promises cannot be reused so it's not like I can reset the same promise every time the onresponse callback happens.

Is there a way to do this via promises? I started reading out generators as well. Would those help too?

Thanks


Solution

  • You could have something like this:

    function sendCommand(data) {
        return new Promise(function(resolve,reject) {
             server.onresponse = resolve;
             server.sendCommand(data);
        });
    }
    

    and use it like this:

    sendCommand({data:"do something"})
    .then(function(data) {
        console.log(data);
        return sendCommand({data:"do something else "})
    })
    .then(function(data) {
        console.log(data);
    })