2017-04-17 65 views
-1

你将如何停止在NodeJs中执行代码的其余部分(而不是用process.exit()声明应用程序只是说这是要执行的最后一行)。如何停止执行NodeJs代码的其余部分?

在正则JavaScript中你有退出(),但似乎并没有在nodejs中工作。

下面的情况是:

connection.query(sql, [req.session.sessionUserPackagePassword] , function(err, rows, fields) { 
    if (!err) { 
    var userFound = false; 
    for(var i=0; i< rows.length; i++) { 
     // Make the comparaison case insensitive 
     if ((rows[i].deliveredToUser).toLowerCase() == `no`) { 
     userFound = true; 
     console.log(userFound); 
     [...] 
    } 
} 
if (!userFound) { 
    res.render('pickup/errorAlreadyDelivered', {}); 
    // exit here 
} 

console.log(userFound); 

// If the query fails to execute 
} else { 
    console.log('Error while performing Query.'); 
    res.render('errorConnection', {}); 
} 
}); 
connection.end(); 




    // Update the query to say the box has been delivered to user and specify time 



// Establish the connection 
[...] 


    res.render('pickup/openPackageClose', { 
      title: '', 
      helpButtonURL: '/help/help-dropPackage', 
      helpButtonTitle: 'Help' 


     }); 



    }); 

本质上讲,当这一条件得到满足,我想不被执行的代码的其余部分

if (!userFound) { 
     res.render('pickup/errorAlreadyDelivered', {}); 
     // exit here 
} 
+0

要停止执行一段代码,请使用break; –

+0

把你想要避免执行的代码放到else块中。 –

+0

您确定要退出而不调用'connection.end()'? –

回答

1

connection.end();然后return;好像它可能工作为你。

+0

这假设你在一个回调函数中,看起来很可能。 –

+0

返回不结束其余的代码。问题是你在下面有另一个res.render,并且一旦if语句被触发,最后的render就会在控制台上显示一个错误,表示不能发送多个头文件。 – John

+0

我更新了代码以提供尝试并使其更加清晰 – John

1

所以根据你对我的其他答案的评论,这听起来像你的程序结构不是我认为的那样。这应该工作:

connection.query(sql, [req.session.sessionUserPackagePassword] , function(err, rows, fields) { 
    if (!err) { 
    var userFound = false; 
    for(var i=0; i< rows.length; i++) { 
     // Make the comparaison case insensitive 
     if ((rows[i].deliveredToUser).toLowerCase() == `no`) { 
     userFound = true; 
     console.log(userFound); 
     [...] 
    } 
} 

if (!userFound) { 
    res.render('pickup/errorAlreadyDelivered', {}); 
    connection.end(); 
} else { 
    console.log(userFound); 
    console.log('Error while performing Query.'); 
    res.render('errorConnection', {}); 
    connection.end(); 
} 
+0

这是您打算发生的事情吗?读这段代码让我觉得逻辑有问题。 –

+0

让我缩进代码并在我的初始帖子中提供更新 – John

+0

感谢您的更新,如果你看看我的操作系统中的更新代码,我不能准确地添加像这样的else条件,因为代码低于连接的末尾,并且问题在于另一个呈现在下面的问题。 – John

相关问题