来自递归承诺的数组 returns 未定义

Array from recursive promises returns undefined

我正在使用 Jake Archibald 的 indexedDB promise wrapper

我有一个对象存储,其中包含 json 个对象和一个单独的自动递增键。当我检索对象时,我还需要获取密钥,以便稍后删除它们。

我正在使用 iterateCursor 递归地遍历游标,以便我可以直接将键和值添加到数组中,我 return 作为已解决的承诺。

static getThings(){

    return thingsDb.then(db => {
        let keyVals = [];

        const tx = db.transaction('things');
        const unsyncedStore = tx.objectStore('things');

        return unsyncedStore.iterateCursor(cursor => {
            if(!cursor) return Promise.resolve(keyVals);
            console.log(`key: ${cursor.primaryKey}, val: ${cursor.value}`);
            keyVals.push({key: cursor.primaryKey, value: cursor.value});
            cursor.continue();
        });
    }).catch(error => {
        console.error(error);
    });

}

然而当我打电话时

DBHelper.getThings().then(returnedArray=> {
  // do something with returnedArray
})

它抛出一个错误,指出 returned 数组未定义。

iterateCursor 没有 return 任何东西(即 return 未定义)

您需要 return promise unsyncedStore.complete

但是这个承诺不会解析为有用的值,所以,使用 .then 到 return keyVals

此外,if(!cursor) return Promise.resolve(keyVals); 没有意义,因为 iterateCursor 回调中的 return 值被忽略了

static getThings() {
    return thingsDb.then(db => {
        let keyVals = [];

        const tx = db.transaction('things');
        const unsyncedStore = tx.objectStore('things');
        // no return here since iterateCursor doesn't return anything useful anyway   
        unsyncedStore.iterateCursor(cursor => {
            if (!cursor) return;
            console.log(`key: ${cursor.primaryKey}, val: ${cursor.value}`);
            keyVals.push({key: cursor.primaryKey, value: cursor.value});
            cursor.continue();
        });
        // return here - complete is a promise that resolves when the iterateCursor completes
        return unsyncedStore.complete.then(() => keyVals);
    }).catch(error => {
        console.error(error);
    });
}