ceiling cat
ceiling cat

Reputation: 564

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

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

Upvotes: 0

Views: 114

Answers (2)

kamoroso94
kamoroso94

Reputation: 1735

You can write a helper function to do just what you described. Pass in the command, and it returns a Promise that resolves with the response from the server. If there is some error handling callback, you should use it as well. For example, let's call it server.onerror. You should replace this with whatever the proper handler is.

function sendCommand(cmd) {
  const promise = new Promise((resolve, reject) => {
    server.onresponse = resolve;
    server.onerror = reject;
  });
  server.sendCommand(cmd);
  return promise;
}

You would use it just like you described, a promise chain. Of course, you probably want to do something with the response rather than just fire the next command. And always remember to handle any errors at the end with catch!

sendCommand({data: "do thing 1"})
  .then((response) => sendCommand({data: "do thing 2"}))
  .then((response) => sendCommand({data: "do thing 3"}))
  .then((response) => console.log("All done!"))
  .catch((error) => console.log("Oops!"));

Upvotes: 0

Federkun
Federkun

Reputation: 36934

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);
})

Upvotes: 1

Related Questions