【发布时间】:2018-10-06 05:36:24
【问题描述】:
我正在使用 localforage 库来访问 localStorage/IndexedDB。要检索项目,调用 localforage.getItem() 函数,该函数返回一个 Promise,该 Promise 在检索数据时完成。
我需要遍历 localforage 键,在符合我的条件的任何键上调用“getItem”,并将该键的值放入“matches”数组中。但是,在我确定所有值已成功添加到“匹配”之前,我不想继续该功能。
我对 Promises 还很陌生,我不知道如何等到所有 getItem() Promise 都实现后再继续。
我意识到 localforage 有一个“迭代”功能,但我真的很想更加精通 Promises 的使用,并且真的很想知道它应该如何工作。
这就是我正在做的事情:
var matches = []; // Array to store matched items
localforage.keys() // Get all keys in localforage
.then(function(keys) // When all keys are retrieved, iterate:
{
for(var i in keys)
{
// If the current key matches what I am looking for, add it to the 'matches' array.
if (keys[i].indexOf('something i am looking for') > -1)
{
// Here I need to add this value to my array 'matches', but this requires using the getItem method which returns a Promise and doesn't necessarily fulfill immediately.
localforage.getItem(keys[i])
.then(function(value)
{
matches.push(value);
});
}
}
});
// At this point, I want to proceed only after *all* matches have been added to the 'matches' array (i.e. the getItem() Promises are fulfilled on all items in the loop).
我该怎么做?这是应用“等待”表达式的地方吗?例如,我应该这样做吗
await localforage.getItem(keys[i])
.then(function(value)
... etc
这会使 getItem 函数同步吗?
感谢您的任何建议/指点。
【问题讨论】:
标签: javascript loops promise es6-promise