Nodejs – Promise代码不执行
我不确定问题是什么……它可能与我的承诺处理。 这是一个nodejs / express应用程序。 我使用Sequelize.js与我的数据库交互,并使用承诺。
本质上,用户可以在下面发布post请求。
现在, condition1
工作正常。 condition3
也可以正常工作。 但是,如果结果是condition2
console.log消息Condition 2 success!
将执行,但res.send('success2!');
代码将不会执行…代码将只是挂在那里。
router.post('/checkUserRoute', function(req, res, next) { const username = req.body.username; if (condition1) { userTable.findOne({ where: { username: username } }).then(function(user) { if (condition2) { console.log('Condition 2 success!') res.send('success2!'); } if (condition3) { user.update({ username: 'NewUserName' }).then(function() { console.log('Condition 3 success!'); res.send('success3!'); }); } }).catch(function(err){ res.send('error'); }); } });
当condition2
被满足并且到达线res.send('success2!');
在我的terminal中显示以下消息:
Warning: a promise was created in a handler at anonymous> ... but was not returned from it, see
,然后显示以下链接:
http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
该链接build议添加return
,但这并没有帮助。
试试这个,有帮助吗?
router.post('/checkUserRoute', function(req, res, next) { const username = req.body.username; if (condition1) { // do you need a return here for the outer router.post? userTable.findOne({ where: { username: username } }).then(function(user) { if (condition2) { console.log('Condition 2 success!') return res.send('success2!'); // added a return here } if (condition3) { // added a return to this line return user.update({ username: 'NewUserName' }).then(function() { console.log('Condition 3 success!'); return res.send('success3!'); // added a return }); } // add a return here indicative of what happens in this condition }).catch(function(err){ res.send('error'); }); } });