簡體   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