我很难理解下面的代码片段的工作流程。
const Circuit = require('circuit-sdk');
const client = new Circuit.Client({
client_id: '<client_id>',
client_secret: '<client_secret>',
domain: 'circuitsandbox.net'
});
client.logon()
.then(user => console.log('Logged on as bot: ' + user.emailAddress))
.catch(console.error);在最后一行中,对象user是如何定义的?或者,另一种方式是,我如何访问user.emailAddress,而无需事先定义它?
这段代码可以工作,它是文档中的一个样本,我只是无法将它输入我的脑海
发布于 2018-05-25 09:17:54
在最后一行中,对象
user是如何定义的?
user是client.logon承诺的解析值。它是由client.logon中解决承诺的代码设置的。当承诺被解析(通过client.logon中的代码)时,您的then处理程序将被调用并将解析值作为参数传递(请记住,user => ...定义了一个接受user参数的函数;更多的是this question's answers)。这就是如何看到它,以及如何使用它的属性(大概是由client.logon创建的)。
例如,client.logon可能看起来像这样(概念上,而不是字面上):
class Client {
// ...
logon() {
return new Promise((resolve, reject) => {
// start the login process, which is presumably asynchronous,
// and then in some handler for completion:
resolve(result); // Where `result` is the user object
});
}
// ...
}logon传递给resolve的值是then处理程序接收的。
当然,logon可能不使用new Promise,它很可能会链接到另一个函数的承诺上,但在某种程度上,这些承诺的最内在部分将通过new Promise (或async,即创建和返回承诺的函数的语法糖)创建承诺。
下面是一个简单的活生生的例子:
class Client {
logon() {
return new Promise((resolve) => {
// Simulate asynchronous process via setTimeout
setTimeout(() => {
resolve({emailAddress: "foo@example.com"});
}, 100);
});
}
}
const client = new Client();
client.logon()
.then(user => console.log(user.emailAddress))
.catch(console.error);
发布于 2018-05-25 09:17:48
您需要将箭头函数看作回调函数,等效于上面的
client.logon()
.then(function(user) {
console.log('Logged on as bot: ' + user.emailAddress)
}.bind(this))
.catch(console.error);如果您想知道.bind(这个)在这里做了什么,它将函数的上下文绑定到调用client.logon的外部上下文。
Arrow函数实现了相同的功能,因为它有自己的this,而不是继承父上下文中的this。
https://stackoverflow.com/questions/50525613
复制相似问题