处理内部异步调用时,函数参数的范围是什么?
What is the scope for a function's arguments when dealing with inner asynchronous calls?
在我的以下示例中,其中一个 express 应用程序回调的参数的行为有所不同,具体取决于它们是否封装在辅助函数中。我已经解决了我的问题,但我想更好地了解这里发生的事情。
getItem
和 buildView
return 使用 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);
});
(区别在第四行和第五行,删掉第四行,修改第五行)
很明显承诺 buildView
被成功解决,否则第一种方法也会失败;在应用 buildView
之前,两种实现都遵循完全相同的步骤。
为什么这些实现不完全相同?
不应该是当 promise buildView
被 resolved 时 .then(res.send)
应该执行 res.send
并将 promise 的 resolved 值作为其参数吗? (即第一个实现)。
以下将起作用:
buildView(item).then(res.send.bind(res)).fail(console.log);
当您简单地执行 then(res.send)
时,res
的 this
上下文丢失:send
函数与 res
对象上下文分离。
它与异步无关,因为这是 JavaScript 中的 known feature of this
。
在我的以下示例中,其中一个 express 应用程序回调的参数的行为有所不同,具体取决于它们是否封装在辅助函数中。我已经解决了我的问题,但我想更好地了解这里发生的事情。
getItem
和 buildView
return 使用 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);
});
(区别在第四行和第五行,删掉第四行,修改第五行)
很明显承诺 buildView
被成功解决,否则第一种方法也会失败;在应用 buildView
之前,两种实现都遵循完全相同的步骤。
为什么这些实现不完全相同?
不应该是当 promise buildView
被 resolved 时 .then(res.send)
应该执行 res.send
并将 promise 的 resolved 值作为其参数吗? (即第一个实现)。
以下将起作用:
buildView(item).then(res.send.bind(res)).fail(console.log);
当您简单地执行 then(res.send)
时,res
的 this
上下文丢失:send
函数与 res
对象上下文分离。
它与异步无关,因为这是 JavaScript 中的 known feature of this
。