繁体   English   中英

如何在循环中使用Promises,并确保在继续执行之前全部实现?

[英]How to use Promises in a loop and ensure all have fulfilled before continuing?

我正在使用localforage库访问localStorage / IndexedDB。 要检索项目,将调用localforage.getItem()函数,该函数返回一个Promise,该Promise在检索数据时完成。

我需要遍历localforage键,在与我的条件匹配的任何键上调用“ getItem”,并将该键的值放在“ matches”数组中。 但是,在确定所有值都已成功添加到“匹配项”之前,我不想继续执行该功能。

我对Promises还是很陌生,因此我无法弄清楚如何继续执行所有getItem()Promises。

我意识到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”表达式的地方吗? 例如,我应该

await localforage.getItem(keys[i])
    .then(function(value)
    ... etc

这会使getItem函数同步吗?

感谢您的任何建议/指针。

您可以在这种情况下使用Promise.all() 基本思想是,您将一堆promise放入和数组中,然后在数组中的所有promise解析后, Promise.all()数组传递给Promise.all()Promise.all()解析为值数组:

localforage.keys()  
    .then(function(keys){  
        var matches = []
        for(let i in keys) {
            if (keys[i].indexOf('something i am looking for') > -1) {
                // matches will be an array of promises
                matches.push(localforage.getItem(keys[i]))
            }
        }
        // Promise.all returns a promise that resolves to an array 
        // of the values they resolve to
        return Promise.all(matches)
    })
    .then(values => {
        // values is an array of your items
    })

您也可以将async/await用于与此类似的东西,其中包括模拟keysgetItems以使代码段运行:

 let localforage = { keys() { return Promise.resolve([1, 2, 3, 4, 5]) }, getItem(k) { return Promise.resolve("found: " + k) } } async function getStuff() { let matches = [] let keys = await localforage.keys() for (let key of keys) { matches.push(await localforage.getItem(key)) } return matches } getStuff() .then(values => { console.log(values) }) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM