Why is the callback in this method located in a thenable, shouldn't the callback be part of the updateAll method return statement?

问题: According to loopback's official docs, the method updateAll takes 3 parameters: where, data, callback, with callback being required. Account.deleteSingleHearingTest = fun...

问题:

According to loopback's official docs, the method updateAll takes 3 parameters: where, data, callback, with callback being required.

Account.deleteSingleHearingTest = function (req, callback) {
    Account.findById(req.accessToken.userId)
        .then(account => {
            if (!account) {
                throw new Error('Cannot find user');
            }
            return app.models.HearingTest.updateAll({ accountId: account.id, id: req.body.hearingTestId }, { isDeleted: new Date() });

        })
        .then(() => {
            callback(null);
        })
        .catch(error => {
            callback(error);
        });
}

I can see that the first two parameters are there, however, the callback doesn't seem to part of the method call. Shouldn't callback be part of the updateAlll method?


回答1:

I'll elaborate on my comment in an answer. I'll bet your code doesn't actually work, you just think it does.

Let's say that the call to updateAll returns something (i.e. does not throw an error) - whether that be null, undefined, true, whatever - then your callback will be called immediately and will not actually wait for your updateAll to perform it's asynchronous operation. Now, if the call to updateAll was sufficiently fast enough, it may appear to you that the code worked when it actually didn't.

This might help illustrate what I mean a bit better:

Promise.resolve()
  .then(function() { return undefined; })
  .then(function() { console.log('it worked!'); });

Two things you can do (not dependent on each other):

  1. Log the return value of updateAll and see if it's a promise
  2. Just stick to what the docs say and use a callback.

Personally, I'd do 1 and then I'd do 2 :)

  • 发表于 2019-01-09 05:18
  • 阅读 ( 168 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除