Reputation: 6271
function getValues() {
return {
first: 1,
second: 2
};
}
function convenientAssignment() {
let first = 0;
let second = 0;
{first, second} = getValues(); // <-- How can this be achieved?
console.log("Values:", first, second);
}
Without using separate assignments like the following:
let values = getValues();
first = values.first;
second = values.second;
This question has nothing to do with concurrency.
Upvotes: 0
Views: 94
Reputation: 2610
You were very close, Use object destructuring to get an objects values into variables.
function simultaneous() {
const {first, second} = getValues(); // <-- et voila!
console.log("Values:", first, second);
}
In your example, where your variables were already declared, you can do:
function convenientAssignment() {
let first = 0;
let second = 0;
({first, second} = getValues()); // <-- et voila!
console.log("Values:", first, second);
}
Upvotes: 3
Reputation: 51441
In your particular case since you've already declared first and second you need to wrap the descructuring assignment in brackets () like so:
function getValues() {
return {
first: 1,
second: 2
};
}
function convenientAssignment() {
let first = 0;
let second = 0;
({first, second} = getValues()); // <-- Note the (...)
console.log("Values:", first, second);
}
Because {first, second}
by itself is considered a block.
Upvotes: 1
Reputation: 74036
This is pretty much what a destructuring assignment is supposed to do:
function getValues() {
return {
first: 1,
second: 2
};
}
let { first, second } = getValues();
console.log( first, second );
// 1 2
Upvotes: 3