我有问题如何对resolve
函数上的 promise 进行send()
,如果socket.write()
导致错误,则在写操作错误时,nodejs 套接字不会引发异常
虽然我仍然在写套接字时从this.socket.on('error',..)
回调中收到通知,但仍然出错,但是仍然无法解决 promise ,因此对send()
的调用被卡住了
我想要的是,用户可以只使用send().then((result) => {})
,如果有错误,他们可以在result
参数上读取它
socket.on('error',(err) => {
console.error(err); //if there are error this will be called
});
async send(data){
return new Promise(resolve, () => {
try{
socket.write(data, 'binary',() => {
resolve(true); //data sent, resolve the promise
});
}
catch(e){ //nodejs socket.write does not throw exception
resolve(false);
}
})
}
//call send, and wait for results
send({..}).then((result) => {
if(result === true){
//send success
}
else {
//send failed
}
});
这一项按预期工作,出现错误时, promise 仍将解决
async send(data){
return new Promise(resolve, () => {
try{
let errorHandler = (err) => {
resolve(false);
}
socket.once('error', errorHandler);
socket.write(data, 'binary',() => {
socket.off('error', errorHandler);
resolve(true); //data sent, resolve the promise
});
}
catch(e){ //nodejs socket.write does not throw exception
resolve(false);
}
})
}
但是,还有更好的解决方案吗? ,因为我不想创建匿名函数并且每次调用
on('error',)
函数时都要调用off('error',)
和send()
最佳答案
您可以检查error
回调中传递的socket.write
参数。
socket.write(data, 'binary',(err) => {
if (err) return reject err;
resolve(true); //data sent, resolve the promise
});
但是建议监听
error
事件。资源:
The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback may or may not be called with the error as its first argument. To reliably detect write errors, add a listener for the 'error' event.
-来自Writable.write() doc
关于javascript - 解决错误时对socket.write的 promise (nodejs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008515/