我正在学习JavaScript语法。我偶尔会看到一种让我困惑的模式:箭头右侧的等号。例如,像这样:
.then(data => myVariable = data)
我不知道该语法中发生了什么。看起来它正在取data
的值并将其分配给名为myVariable
的变量。有人可以解释一下吗?
答案 0 :(得分:3)
data
的值赋给myVariable
并返回右侧,尽管这可能不是在这种情况下使用。
在一个更简化的案例中:
let foo = 3;
function foobar(callback) {
const result = callback(5); //call callback with 5 as argument
console.log(result); //5
}
foobar(five => foo = five); //assigns 5 to foo
console.log(foo); //5
这通常不是最易读的选项,您的问题证明了这一点。我建议像这样添加一个块(如果你不打算实际返回右侧值):
myPromise.then(data => {
myVariable = data;
});
在这种情况下,赋值表达式的右侧没有隐式返回,并使意图更清晰。此外,不鼓励使用您对异步承诺所假设的内容进行分配。
除了使用可能遇到some problems if not used correctly的变量赋值之外,可能会查看async / await或其他新的ES功能来处理异步代码。
答案 1 :(得分:0)
This is called fat arrow function in ES 6 . It is used for many purposes like
1.Arguments
If we want to pass and argument to a function.
Old Syntax :
let sum = function(x,y){
return x+y;
}
New Syntax with fat arrow
let sum = (x,y) => x+y;
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
Note : Return statement is not required in fat arrow of it is only one line .
2. Anonymous Function.
// ES5
API.prototype.get = function(resource) {
var self = this;
return new Promise(function(resolve, reject) {
http.get(self.uri + resource, function(data) {
resolve(data);
});
});
};
Using an arrow function, the same result can be achieved more concisely and clearly:
// ES6
API.prototype.get = function(resource) {
return new Promise((resolve, reject) => {
http.get(this.uri + resource, function(data) {
resolve(data);
});
});
};