首页 文章

当我在try-catch中使用setTimeout时返回不起作用

提问于
浏览
1

我有这个try-catch块:

async function matchMaking(userId) {
  try {

    const user = await User.findOne({
      _id: userId
    });

    var timeOut1 = setTimeout(function() {
      return {
        success: false,
        msg: "matchMaking aleready done"
      };
    }, 20000);

    //some code
    if (match === true) {
      clearTimeout(timeOut1);
      return {
        success: true
      };
    }

  } catch (e) {
    return {
      success: false,
      error: e
    };
  }
}

我用它如下:

matchMaking(userId).then(res => {
  if (res.success) {
    console.log("success")
  } else {
    console.log("failed")
  }
});

当(匹配=== true)它确定并且我在控制台中获得“成功”时,但是当(匹配===假)时,我希望在20秒后在控制台中看到“失败” . 但是返回在setTimeout中不起作用,我什么也得不到 .

1 回答

  • 0

    您需要从matchMaking函数返回 Promise .

    async function matchMaking (userId) {
    
        return new Promise((res, rej) => {
            const user = await User.findOne({
                _id: userId
            });
            var timeOut1 = setTimeout(function() {
                return res({
                    success: false,
                    msg: "matchMaking aleready done"
                });
            }, 20000);
    
            if (match === true) {
                clearTimeout(timeOut1);
                return res({
                    success: true
                });
            }
        });
    }
    

    这样,当你这样调用它时 - 它将按预期运行:

    matchMaking(userId).then(res => {
      if (res.success) {
        console.log("success")
      } else {
        console.log("failed")
      }
    });
    

    处理它的更好方法是使用promise的 reject 回调:

    async function matchMaking (userId) {
    
        return new Promise((res, rej) => {
            const user = await User.findOne({
                _id: userId
            });
            var timeOut1 = setTimeout(function() {
                return rej({
                    success: false,
                    msg: "matchMaking aleready done"
                });
            }, 20000);
    
            if (match === true) {
                clearTimeout(timeOut1);
                return res({
                    success: true
                });
            }
        });
    }
    

    这样,当您这样调用它时 - 您可以使用 .catch() 来处理失败状态:

    matchMaking(userId)
        .then(res => console.log("success"))
        .catch(err => console.log("failed"));
    

相关问题