在javascript中传递箭头函数中的对象

时间:2018-05-25 09:14:12

标签: javascript

我很难理解以下代码段的工作流程

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

这段代码有效,它是来自纪录片的样本,我无法将它放到我的脑海中

2 个答案:

答案 0 :(得分:1)

  

如何在第二行中定义对象user

user是来自client.logon的承诺的分辨率值。它由client.logon中的代码设置,可以解析承诺。当解析了promise(通过client.logon中的代码)时,会调用then处理程序并将解析值作为参数传递(请记住user => ...定义了一个接受{{1}的函数参数; this question's answers中的更多内容。这就是你如何看待它,以及如何使用它的属性(可能是由user创建的)。

例如,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,它是创建并返回一个promise的函数的语法糖。)

这是一个简单的实例:

async

答案 1 :(得分:0)

您需要将箭头函数视为回调函数,与上面的函数相同

client.logon()
  .then(function(user) {
        console.log('Logged on as bot: ' + user.emailAddress)
  }.bind(this))
  .catch(console.error);

如果你想知道.bind(this)在这里做了什么,它将函数的上下文绑定到调用client.logon的外部上下文。

箭头函数实现相同,因为它没有自己的this,而是从父上下文继承this