2016-12-31 81 views
0

我正在用节点js写我的后端,而且由于我对节点及其异步本质相当陌生,因此需要澄清。我试图实现的是在身份验证失败的情况下从中间件功能返回。我可以通过在每个条件之后使用return;来实现,但是这样我必须为每个条件设置res对象的一些值。例如:从失败时返回函数

if(recvToken) { 
    try { 
     let tokenVal = jwt.decode(recvToken, app.get('jwtToken')); 
     if(tokenVal.exp < Date.now()) { 
     res.status(401).json({ 
      success: false, 
      message: 'Auth failed', 
      details: 'Some other details' 
      // And a few more fields 
     }); 
     } 
     else if(tokenVal.mode !== 'cust') { 
     res.status(401).json({ 
      success: false, 
      message: 'Auth failed', 
      details: 'Some other details' 
      // And a few more fields 
     }); 
     } 
     else { 
     // A few more conditions, you get the gist 
     } 
    } 
    catch (err) { 
     return; 
    } 
    } 
    else { 
    return; 
    } 

这是行得通的。但我想有一个函数来处理所有这些失败。我搞砸了一下周围,并结束了一句:

function handleFailure(res, cb) { 
    res.status(401).json({ 
    message: 'Not authorized' 
    }); 
    cb(); 
} 

这是从所有的条件代码调用,如:

if(tokenVal.mode !== 'cust') { 
    handleFailure(res, function() { return; }); 
} 
else if(tokenVal.exp < Date.now()) { 
    handleFailure(res, function() { return; }); 
} 

确保它看起来干净,但它并没有因为工作的回报在回调函数中,从回调函数返回而不是父函数。 有没有这种类型的东西可以做到从调用handleFailure的函数返回?提前致谢!

+0

为什么您需要将回调传递给'handleFailure'?由于它全部是同步的,你可以返回。 – schroffl

+0

@schroffl如果没有设置res对象,是否不可能从函数返回?如果没有,我觉得这个问题很愚蠢...... – Zeokav

+0

“没有设置res对象”是什么意思?如果我正确地解释了你的问题:你可以在调用'res.status'之前返回,或者在if语句中包装所有东西。 – schroffl

回答

1

一个简单的解决方案是让句柄失效不需要回调。

function handleFailure(res) { 
    res.status(401).json({ 
    message: 'Not authorized' 
    }); 
} 

// Somewhere else in the code 
if(tokenVal.mode !== 'cust') { 
    handleFailure(res); 
    return; 
} 
else if(tokenVal.exp < Date.now()) { 
    handleFailure(res); 
    return; 
} 
+0

感谢您的回答。这两个答案都是有意义的,而且它们都起作用,因为它们基本上都是一样的。意识到我甚至不需要回拨! – Zeokav

+0

Jonty几秒钟快一点:P 是的,他们也是这样做的,因为'handleFailure'返回undefined。 –

+0

安东尼奥,这发生在我身上很多次xD –

0

你可以返回handleFailure功能,所以当前函数的执行结束,并在同一时间,你正在处理的故障(发回401响应)。

function handleFailure(res) { 
    res.status(401).json({ 
    message: 'Not authorized' 
    }); 
} 

if(tokenVal.mode !== 'cust') { 
    return handleFailure(res); 
} 
else if(tokenVal.exp < Date.now()) { 
    return handleFailure(res); 
}