在socket-io事件上拒绝承诺并停止超时 [英] Reject a promise and stop timeout on socket-io event

查看:69
本文介绍了在socket-io事件上拒绝承诺并停止超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下函数在Node.js服务器脚本中模拟等待(睡眠).

I'm currently using the following function to simulate awaiting (sleep) in my Node.js server script.

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

,并且我正在使用它,如下所示.以这种方式使用时,该行下面的代码将暂停执行,直到经过20秒为止.

and I'm using it like below. When used in this way, executing the code below that line is paused until 20 seconds have been passed.

await sleep(20000)

现在,我想在socket-io事件上打破这种睡眠状态,但是我找不到正确的解决方法.

Now I want to break this sleeping on a socket-io event, but I can't figure a correct way out to do that.

我尝试了以下代码,但并没有破坏睡眠.

I tried the following code, but it didn't break the sleep.

// This object holds some properties
var meetings = {

}

function sleep(ms) {
  return new Promise(function(resolve,reject) => {
    var t = setTimeout(resolve, ms)
    // add the function as a "meetings" object property value
    meetings[endSleep] = function(){
      clearTimeout(t)
      reject()
    }    
  });
}

// later, using socket-io
socket.on("end_sleep",function(){
  meetings["endSleep"]()
})

我如何才能使用此功能?所有有用的建议都将受到高度赞赏.

How can I get this functionality to work? all helpful suggestions are highly appreciated.

推荐答案

在您的情况下,"break"表示及早解决",而不是拒绝.如果调用拒绝,则await语句将引发错误,并且可以停止执行异步函数(如果未使用try catch块).该代码可能看起来更好一些::

In your case 'break' means 'early resolving', not rejecting. If you calling reject the await statement will throw an error and execution of the async function can be stopped (if try catch block is not used). The code might look a little better::

const CPromise= require("c-promise2");
// cancellable sleep
function sleep(ms, signal) {
    return new CPromise((resolve, reject, {onCancel}) => {
        const timer = setTimeout(resolve, ms);
        onCancel(() => clearTimeout(timer));
    }, {signal}).catch(() => {});
}

(async()=>{
    const sleeper= sleep(30000);
    socket.on("end_sleep",function(){
        sleeper.cancel();
    });
    await sleeper;
})();

const abortController= new CPromise.AbortController();

(async()=>{
    await sleep(30000, abortController.signal);
})();

socket.on("end_sleep",function(){
    abortController.abort();
});

这篇关于在socket-io事件上拒绝承诺并停止超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆