简体   繁体   English

无法在Promise回调中写入socketio?

[英]Unable to write to socketio within Promise callback?

If I move socket.emit outside of that function, the socket emit event happens. 如果我将socket.emit移到该函数之外,则会发生套接字发射事件。 However, I need to get a hold of 'values' data, which is in the promise call back. 但是,我需要保留“值”数据,这在promise回调中。 The socket emit event in that case doesn't happen. 在这种情况下,套接字发射事件不会发生。

app.io.on('connection', function(socket) {
  setInterval(function() {
    var bitfinex = new Promise(
      function(resolve, reject) {
        const orderBook = 'https://api.bitfinex.com/v2/book/tBTCUSD/P0'
        axios.get(orderBook)
          .then(function(response) {
            resolve(response)
          })
          .catch(function(error) {
            reject(error)
          });
      });

    var bitmex = new Promise(
      function(resolve, reject) {
        const orderBook = 'https://www.bitmex.com/api/v1/orderBook/L2?symbol=xbt&depth=25'
        axios.get(orderBook)
          .then(function(response) {
            resolve(response)
          })
          .catch(function(error) {
            reject(error)
          });
      });
    Promise.all([bitmex, bitfinex]).then(values => {
      socket.emit('feed', {
        data: values
      })
    });
  }, 3000)

Axios is returning a promise so you don't need to create new Promise and you should catch your error if there is any: Axios正在返回一个承诺,因此您无需创建新的Promise,并且如果存在任何错误,则应该捕获错误:

app.io.on(
  'connection', 
  function (socket) {
    setInterval(
      function () {
        Promise.all(
          [
            axios.get('https://api.bitfinex.com/v2/book/tBTCUSD/P0'),
            axios.get('https://www.bitmex.com/api/v1/orderBook/L2?symbol=xbt&depth=25')
          ]
        ).then(values =>
          socket.emit(
            'feed',
            {
              data: values
            }
          )
        )
        .catch(
          e => console.warn("something went wrong:",e)
        )
      },
      3000
    )
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM