Nodejs websockets client pending promise

2019-07-25 14:33发布

问题:

Trying to capture all the data from a websocket connection as a nodejs client using a promise. Script is exiting before all the messages are received and console.logging 'Promise { <pending> }', I expected it to log 'response #1 | goodbye'.

const WebSocket = require('ws');
const ws = new WebSocket('wss:url');

let results = new Promise(function(resolve, reject) {
    ws.on('open', function open() {
      ws.send('hello');
    });
    let receivedResults = '';
    ws.on('message', function incoming(data) {
        if (data == 'goodbye') {
            receivedResults += ' | ' + data;
            resolve(result);
        } else {
            receivedResults = data;
        }
    });
});
console.log(results);

回答1:

For it to log response #1 | goodbye you will need to wait for it to resolve.

results.then(data => console.log(data));


回答2:

At the moment you are printing results it is just a promise object in pending status waiting for resolve, you will not get the result at that moment, it was just recently created. To wait for the resolve you need to execute 'then' method of the promise:

results.then(myResponse => {
 console.log(myResponse);
 // do more...
});

I recommend this talk to understand the async behavior on node.js https://www.youtube.com/watch?v=8aGhZQkoFbQ