我的代码:
const users = [ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]
p = new Promise( resolve => resolve(users) )
p.then( (user) => console.log(user) )
返回以下日志:
[{id:1,name:' user1' },{id:2,name:' user2' }]
如果我按以下方式更改,
users.then( ([user]) => console.log(user) )
我收到以下日志:
{id:1,姓名:' user1' }
我不太明白为什么第二个只记录数组中的第一个元素。
答案 0 :(得分:4)
@Slf4j
@Configuration
@EnableIntegration
public class MyMailAdapter {
@Autowired
EmailConfig emailCfg;
@Bean
public SubscribableChannel mailChannel() {
log.info("Channel ready");
return MessageChannels.direct().get();
}
@Bean
public ImapMailReceiver receiver() {
ImapMailReceiver mailReceiver = new ImapMailReceiver(emailCfg.getImapUrl());
mailReceiver.setJavaMailProperties(javaMailProperties());
mailReceiver.setShouldDeleteMessages(false);
mailReceiver.setShouldMarkMessagesAsRead(true);
return mailReceiver;
}
@Bean
public ImapIdleChannelAdapter adapter() {
ImapIdleChannelAdapter imapIdleChannelAdapter = new ImapIdleChannelAdapter(receiver());
imapIdleChannelAdapter.setOutputChannel(mailChannel());
imapIdleChannelAdapter.afterPropertiesSet();
return imapIdleChannelAdapter;
}
@ServiceActivator(inputChannel = "mailChannel")
public void receive(Message<MimeMessage> mail) throws MessagingException {
log.info(mail.getPayload().toString());
}
private Properties javaMailProperties() {
Properties javaMailProperties = new Properties();
javaMailProperties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailProperties.setProperty("mail.imap.socketFactory.fallback", "false");
javaMailProperties.setProperty("mail.store.protocol", "imaps");
javaMailProperties.setProperty("mail.debug", "true");
javaMailProperties.setProperty("mail.imap.ssl", "true");
return javaMailProperties;
}
}
&#13;
但是如果你只构造一个,你得到数组的第一个值
[a, b, c] = [1, 2, 3]
console.log(a)
console.log(b)
console.log(c)
&#13;
至于你的例子,可以在许多地方进行解构,例如函数参数
答案 1 :(得分:0)
Destructuring是 ES6 又名 ECMA2015 功能。
您可以解构Array
和Objects
。
Object
解构如下:允许您使用简单的语法从keys
获取您想要的object
。
const obj = {
a: 'a',
b: 'b',
c: 'c',
};
// Without object destructuring
const a_ = obj.a;
const b_ = obj.b;
// With object destructuring
const {
a,
b,
} = obj;
console.log(a);
Array
解构完全相同,但您不是指定要获得的keys
,而是使用index
数据。
const arr = [
'a',
'b',
'c',
];
// Without array destructuring
const a_ = arr[0];
const c_ = arr[2];
// With array destructuring
const [
a, , c,
] = arr;
console.log(c);
您可以在任何地方使用Array
和Object
解构;包括在函数参数中。在这种情况下,它特别好,因为您可以轻松地将default
值分配给keys
,如下所示
function func({
a,
b,
c = 'default',
}) {
console.log(a, '/', b, '/', c);
}
func({
a: 'j\'aime la france',
b: 'vive les baguettes',
});