为什么这两个函数调用不相等

Why are these two function calls not equal to each other?

本文关键字:两个 函数调用 不相等 为什么      更新时间:2023-09-26

对不起,如果标题太模糊,我不知道如何更好地解释它。

为什么在这种情况下使用匿名函数调用有效:

  Team
    .findAll()
    .then(function(teams) {
      res.send(teams);
    });

但是将res.send直接传递到.then()中,它不起作用:

  Team
    .findAll()
    .then(res.send);

这会导致此错误:

Possibly unhandled TypeError: Cannot read property 'method' of undefined
    at res.send (/opt/web/projects/node_modules/express/lib/response.js:83:27)
    at Promise._settlePromiseAt (/opt/web/projects/node_modules/sequelize/lib/promise.js:76:18)
    at process._tickCallback (node.js:442:13)

这两者不是相等的吗? res.send只接受一个参数,所以它不像是将一些奇怪的未知参数传递给函数。

.then() 方法希望你给它传递一个函数,因为它(最终)会调用它。如果你只是传递一个(非函数)值,那是不可能的。

打电话给.then()的目的是说:"手术完成后,请这样做

编辑 — 啊,好的,对不起。在这种情况下,问题是当您传递res.send时,send方法将丢失上下文。也就是说,当 Promise 机制调用 send 函数时,它不会知道res的值。

你可以这样做:

  .then(res.send.bind(res))

通过这样做,可以确保在最终调用send时,将调用它,以便this将成为对res对象的引用。