Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make promise from web-socket API? #21

Open
allawitte opened this issue Sep 25, 2018 · 3 comments
Open

How to make promise from web-socket API? #21

allawitte opened this issue Sep 25, 2018 · 3 comments

Comments

@allawitte
Copy link

allawitte commented Sep 25, 2018

Thank you for your video!
I do application on nodejs what request some data on external server and relay them to some external client via TCP.
Do you have an idea how to make promise from the code like:

const Market = require('some-api');
myMarket = new Market();
myMarket.websockets.trades(request[1], (trades, error) => {
  if (error) {
    send to external client(error);
  }
  if(this.streamStatuse === 1) {
    send to external client(JSON.stringify(['TR', this.getTimeString(), trades]));
  }
});
@shama
Copy link
Owner

shama commented Sep 26, 2018

There is a non-standard API Promise.denodeify to help convert Node.js compatible callbacks to promises but that API signature in your example doesn't match the Node.js standard of error first in callbacks.

But you can just wrap it in a promise to turn it into a promise:

const Market = require('some-api');
const promise = new Promise((resolve, reject) => {
  const myMarket = new Market();
  myMarket.websockets.trades(request[1], (trades, error) => {
    if (error) {
      reject(error);
      return;
    }
    if (this.streamStatus === 1) {
      resolve(JSON.stringify(['TR', this.getTimeString(), trades]));
    } else {
      reject(new Error('This promise wasnt handled'));
    }
  });
});

promise
  .then((json) => { /* do stuff with json */ })
  .catch((err) => { /* do stuff with err */ })

@allawitte
Copy link
Author

allawitte commented Sep 26, 2018 via email

@shama
Copy link
Owner

shama commented Sep 26, 2018

Ah ha, I see. If (trades, error) => {} gets called multiple times then it's effectively an Event Emitter. In which case you shouldn't use a promise here. Promises are intended to be resolved a single time so they're not a very good API for events.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants