如何使用异步等待来防止在 array.length 个对象上获取 0?
how to use async await to prevent getting 0 on array.length of objects?
我在这里做的是在 localStorage 中搜索一些数据,然后我将这些数据(对象)推送到 array.Later 我想循环这个对象数组,但问题是长度是 0.I 知道我必须使用 async await 但我不了解它是如何工作的。
this.afAuth.authState.subscribe(user => {
if (user) {
this.Uid = user.uid;
this.storage.get(this.Uid ).then((val) => {
this.CaloriesChartData = JSON.parse(val);
if (this.CaloriesChartData != null) {
this.CaloriesChartData = Object.keys(this.CaloriesChartData).map(key => ({ type: key, value: this.CaloriesChartData[key] }));
this.CaloriesChartDataLength = this.CaloriesChartData.length;
for (let i = 0; i < this.CaloriesChartDataLength; i++) {
this.CaloriesArray.push(this.CaloriesChartData[i].value);
}
}
console.log(this.CaloriesArray);
console.log(this.CaloriesArray.length);
});`
我正在为数组获取一个 [],但是当我展开它时它已满
长度为 0。
this.storage.get(this.Uid )
returns 一个承诺。 Promise 是你必须等待的东西。因此,您需要使用 await this.storage.get(this.Uid )
。
但是如果使用异步等待,您还希望将返回值存储在某个地方并且不使用 Promise 链。例如 const data = await this.storage.get(this.Uid )
。
现在您可以解析数据而不是 val。
由于 await 只能在异步函数中使用,因此您必须将箭头函数更改为异步函数,例如:
this.afAuth.authState.subscribe(async user => {
总计:
this.afAuth.authState.subscribe(async user => {
if (user) {
this.Uid = user.uid;
const data = await this.storage.get(this.Uid );
this.CaloriesChartData = JSON.parse(data);
if (this.CaloriesChartData != null) {
...
我在这里做的是在 localStorage 中搜索一些数据,然后我将这些数据(对象)推送到 array.Later 我想循环这个对象数组,但问题是长度是 0.I 知道我必须使用 async await 但我不了解它是如何工作的。
this.afAuth.authState.subscribe(user => {
if (user) {
this.Uid = user.uid;
this.storage.get(this.Uid ).then((val) => {
this.CaloriesChartData = JSON.parse(val);
if (this.CaloriesChartData != null) {
this.CaloriesChartData = Object.keys(this.CaloriesChartData).map(key => ({ type: key, value: this.CaloriesChartData[key] }));
this.CaloriesChartDataLength = this.CaloriesChartData.length;
for (let i = 0; i < this.CaloriesChartDataLength; i++) {
this.CaloriesArray.push(this.CaloriesChartData[i].value);
}
}
console.log(this.CaloriesArray);
console.log(this.CaloriesArray.length);
});`
我正在为数组获取一个 [],但是当我展开它时它已满 长度为 0。
this.storage.get(this.Uid )
returns 一个承诺。 Promise 是你必须等待的东西。因此,您需要使用 await this.storage.get(this.Uid )
。
但是如果使用异步等待,您还希望将返回值存储在某个地方并且不使用 Promise 链。例如 const data = await this.storage.get(this.Uid )
。
现在您可以解析数据而不是 val。
由于 await 只能在异步函数中使用,因此您必须将箭头函数更改为异步函数,例如:
this.afAuth.authState.subscribe(async user => {
总计:
this.afAuth.authState.subscribe(async user => {
if (user) {
this.Uid = user.uid;
const data = await this.storage.get(this.Uid );
this.CaloriesChartData = JSON.parse(data);
if (this.CaloriesChartData != null) {
...