【问题标题】:What is the scope for a function's arguments when dealing with inner asynchronous calls?处理内部异步调用时,函数参数的范围是什么?
【发布时间】:2016-04-26 00:08:10
【问题描述】:

在下面的示例中,快速应用程序回调之一的参数的行为会有所不同,具体取决于它们是否封装在辅助函数中。我已经解决了我的问题,但我想更好地了解这里发生了什么。

getItembuildView 返回使用 Q 创建的承诺。 以下代码有效(即从未调用过失败回调):

var app = require("express")();
app.get('/item/:itemId', function(req, res){
    var showItem= function(item){
        var s = function(x){res.send(x);};
        buildView(item).then(s).fail(console.log);
    };

    var showError = function(error){
        res.send(error.message);
    };

    getItem(req.params.exception_id)
        .then(showItem).fail(showError);
});

以下代码没有(console.log 打印 [TypeError: Cannot read property 'req' of undefined]):

var app = require("express")();
app.get('/item/:itemId', function(req, res){
    var showItem= function(item){
        buildView(item).then(res.send).fail(console.log);
    };

    var showError = function(error){
        res.send(error.message);
    };

    getItem(req.params.exception_id)
        .then(showItem).fail(showError);
});

(区别在第四行和第五行,第四行删除,第五行修改)。

很明显,promise buildView 正在被成功解决,否则第一种方法也会失败;在应用buildView 之前,两个实现都遵循完全相同的步骤。

为什么这些实现不完全相同? 不应该是当 promise buildView 被解析时 .then(res.send) 应该以 promise 的解析值作为参数执行 res.send 吗? (即第一个实现)。

【问题讨论】:

  • 你可以试试buildView(item).then(res.send.bind(this)).fail(console.log);buildView(item).then(res.send.bind(res)).fail(console.log); 吗?
  • buildView(item).then(res.send.bind(res)) 为函数绑定正确的上下文。忘了在javascript中this有点太特别了。

标签: node.js asynchronous express q


【解决方案1】:

以下将起作用:

buildView(item).then(res.send.bind(res)).fail(console.log);

当您简单地执行then(res.send) 时,resthis 上下文丢失:send 函数与res 对象上下文分离。

它与异步无关,因为这是 JavaScript 中的 known feature of this

【讨论】:

  • 第二个应该可以。第一个肯定是错的。但是如果你能解释为什么会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 2021-01-17
  • 2017-04-17
  • 2021-08-07
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多