简体   繁体   English

Function 在返回后继续执行

[英]Function continues execution even after return

My question is simple, when I run the following code and check the DB, I find that the user is deleted successfully, that means the User.findOneAndDelete is executed, promise is fulfilled and I expect to see { success: 'user_deleted' } in the response;我的问题很简单,当我运行以下代码并检查数据库时,我发现用户已成功删除,这意味着User.findOneAndDelete已执行,promise 已完成,我希望看到{ success: 'user_deleted' } in响应; however, I am getting { error: 'user_not_found' } which is supposed to happen ONLY if User doesn't exist which isn't the case here because the code inside the IF block is executed as per my observation in the DB.但是,我收到{ error: 'user_not_found' }这应该仅在用户不存在时才会发生,这里不是这种情况,因为 IF 块内的代码是根据我在数据库中的观察执行的。

User.exists({ username}).then(exists => {
    if (exists) {
      User.findOneAndDelete({ username }).then(() => {
        res.json({ success: 'user_deleted' });
        return;
      }
      ).catch(err => {
        res.json({ error: 'user_delete_fail' });
        return;
      })
    };
    res.json({ error: 'user_not_found' })
    return;
  });

Now to solve this I tried to add an else statement instead of the implicit way I was doing it before, and it worked as expected and I got `{ success: 'user_deleted' } in the response.现在为了解决这个问题,我尝试添加一个else语句,而不是我之前做的隐式方式,它按预期工作,我在响应中得到了 `{ success: 'user_deleted' }。

User.exists({ username}).then(exists => {
    if (exists) {
      User.findOneAndDelete({ username }).then(() => {
        res.json({ success: 'user_deleted' });
        return;
      }
      ).catch(err => {
        res.json({ error: 'user_delete_fail' });
        return;
      })
    } else {
      res.json({ error: 'user_not_found' })
      return;
    };
  });

My question is: Why is this behavior happening?我的问题是:为什么会发生这种行为? Why is execution jumping to the bottom of the function already?为什么执行已经跳到 function 的底部? And why when it goes to the bottom of the function and responds, how does the delete occur and the User is deleted in the DB, I am quite confused here.以及为什么当它走到function的底部并响应时,删除是如何发生的并且用户在数据库中被删除,我在这里很困惑。

EDIT: It also behaves as expected when I convert the parent function to an async function and use await on the DB operation.编辑:当我将父 function 转换为async function 并在 DB 操作上使用 await 时,它的行为也符合预期。

The problem with your code is the last res.json({ error: 'user_not_found' }) call.您的代码的问题是最后一个res.json({ error: 'user_not_found' })调用。

If you look carefully, this line is getting fired even before the inner delete query is fired as inner query is asynchronous.如果你仔细看,这一行甚至在内部删除查询被触发之前就被触发了,因为内部查询是异步的。

So in first scenario the function always returns the response regardless user exists or not.所以在第一种情况下,无论用户是否存在,function 总是返回响应。

putting else in your code block basically performs either this or that logic so if user exists, res.json({ error: 'user_not_found' }) will never get called.将 else 放在您的代码块中基本上执行either this or that逻辑,所以如果用户存在, res.json({ error: 'user_not_found' })将永远不会被调用。

EDIT: Alternative Code Using Async-Await编辑:使用 Async-Await 的替代代码

Using async-await in this case would make more sense as it simplifies the code, check following code which should do exactly what you want without use of else .在这种情况下使用async-await会更有意义,因为它可以简化代码,请检查以下代码,它应该完全符合您的要求,而无需使用else

It also avoids nesting which makes code simpler它还避免了嵌套,使代码更简单

User.exists({ username }).then(async exists => {
    try {
        if (exists) {
            // this await will remove the need of inner promise chaining
            await User.findOneAndDelete({ username });
            res.json({ success: 'user_deleted' });
        }
        // in this case, this will no longer be performed before delete query
        res.json({ error: 'user_not_found' });
    } catch (error) {
        res.json({ error: 'user_delete_fail' });
    }
});

PS - You can have similar async-await for User.exists API provided its parent function is marked as async . PS - 你可以有类似async-await User.exists API 如果它的父 function 被标记为async

I hope this helps.我希望这有帮助。

findOneAndDelete returns a Promise , which will not block the execution of the remaining code (except when, as you pointed out, the function is async and you await it). findOneAndDelete返回一个Promise ,它不会阻止剩余代码的执行(除非,正如您所指出的, function 是async的并且您等待它)。 Furthermore you are not returning from the if branch ( return inside the then will only return from the callback in then ) and thus the remaining code outside will be executed either way.此外,您不会从 if 分支return (在then中的 return 只会从then中的回调返回),因此外部的剩余代码将以任何一种方式执行。 It probably only works if you await (without return ) because the response is already sent at the point.它可能仅在您 await (没有return )时才有效,因为此时已经发送了响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM