处理内部asynchronous调用时,函数参数的作用域是什么?
在我的下面的例子中,其中一个快速应用callback的参数行为有所不同,取决于它们是否封装在辅助函数中。 我已经解决了我的问题,但我想更好地了解这里发生了什么。
getItem
和buildView
返回使用Q
创build的buildView
。 下面的代码工作(即没有失败callback被称为):
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
的时候,两个实现都遵循完全相同的步骤。
为什么这些实现不完全一样? 应该不是,当承诺buildView
被parsing。然后.then(res.send)
应该执行res.send
与promise的parsing值作为其参数? (即第一次执行)。
以下将起作用:
buildView(item).then(res.send.bind(res)).fail(console.log);
当你简单的做then(res.send)
, res
this
上下文就会丢失: send
函数从res
对象上下文中分离出来。
它与asynchronous性无关,因为这是JavaScript中已知的特性 。