Nodejs websockets 客户端待定承诺 [英] Nodejs websockets client pending promise
本文介绍了Nodejs websockets 客户端待定承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用承诺从作为 nodejs 客户端的 websocket 连接中捕获所有数据.脚本在收到所有消息和 console.logging 'Promise { <pending> 之前退出}'
,我预计它会记录响应 #1 |再见'.
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);
推荐答案
为了记录 response #1 |再见
你需要等待它解决.
For it to log response #1 | goodbye
you will need to wait for it to resolve.
results.then(data => console.log(data));
这篇关于Nodejs websockets 客户端待定承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文