【发布时间】:2023-04-07 09:10:02
【问题描述】:
我正在设置以下函数以便在之后检索它。 但是,由于某种原因,它不起作用:
constructor(private nativeStorage: NativeStorage) {
// I am calling it this way:
this.userId = 123;
this.getItem("userId", this.userId);
// If I replace the shortcut by the below it works fine
/* this.nativeStorage.getItem("userId).then(
data => this.userId = data,
error => console.error(error)
); */
}
getItem(itemKey, itemValue) {
return this.nativeStorage.getItem(itemKey).then(
data => itemValue = data,
error => console.error(error)
);
}
我相信我在这里遗漏了一些东西,这就是它不起作用的原因
【问题讨论】:
-
你希望这个函数
data => itemValue = data做什么? -
什么不起作用?
-
this.nativeStorage.getItem(itemKey)是一个承诺?试试then和catch -
itemValue是一个局部变量。重新分配它在getItem()之外没有任何影响。您是否尝试隐式更新this.userId? -
然后查看@ibrahimmahrir 的答案。 JS 不支持类似的功能。除此之外,这还有另一个缺陷:
this.nativeStorage.getItem()是异步的。你不知道this.userId = data的更新何时会发生。 100 毫秒(你几乎没有注意到)对于 JS 代码来说就像几个小时。除非您处理承诺,否则this.userId上的任何代码仍可能处理旧值。
标签: javascript function ecmascript-6