您问题中的代码存在一些问题,导致其无法正常工作。它归结为异步操作的顺序,这里用 Promises 表示。
基本上,then 回调中的所有内容都在方法中的其余代码之后执行。
我用数字 0 - 6 表示了操作在逻辑上发生的顺序。
var allBlogs = []; // 0
this.storage.get('products').then((val) => { // 1
console.log(val + " = previous value"); // 5
allBlogs.push(val); // 6
});
allBlogs.push(this.navParams.get('id')); // 2
console.log(allBlogs); // 3
this.storage.set('products', allBlogs); // 4
理解这一点的关键是要意识到一个promise解析或拒绝函数,我们传递给then或catch的函数是在Promise所代表的异步操作完成时执行的。
Ionic 的Storage.get 和Storage.set 是基于Promise 的API,您需要正确组合它们以便操作以正确的顺序发生。新 id 确实被添加到 allBlogs 数组中,但之后它被持久化了。
最简单、最优雅的方法是使用async/await。
你可以使用类似的东西
const key = 'products';
constructor(readonly storage: Storage, navParams: NavParams) {
const {id} = navParams.data;
this.updateStorage(id).catch(reason => console.error(reason));
}
async updateStorage(newId) {, f
const storedIds = await this.storage.get(key) || [];
const updatedIds = [...storedIds, newId];
await this.storage.set(key, updatedIds);
}
当我们使用async 函数时,代码的编排会发生变化,以便动作按照编写顺序进行编排,前提是await 使用在正确的位置。这是语法上的便利。
如果您只想添加不存在的项目,您可以在插入之前使用Array.prototype.includes 检查是否存在。
async ensureId(id) {
const storedIds = await this.storage.get(key) || [];
if (storedIds.includes(id)) {
return;
}
const updatedIds = [...storedIds, id];
await this.storage.set(key, updatedIds);
}