解决嵌套的promise后运行函数

时间:2018-05-06 11:07:27

标签: javascript promise

我有一个实用程序函数,用于检查indexeddb中的项目并使其无效

this.invalidateCache().then(() => { // 2nd promise has finished its work
    // check the db
    this.getCachedResponse()
        .then((res) => {
            if (res) {} // item is not expired
            else {} // make http request

现在我需要确保第二个承诺在我链接到另一个函数之前已经解决,就像这样

this.invalidateCache().then(()

但不幸的是2nd解决了第一个承诺而不是嵌套。

那么如何在嵌套import csv with open('data.csv', 'w') as outfile: writer = csv.DictWriter(outfile, ['Commodities', 'Area', 'Type'], delimiter=';') writer.writeheader() for l in links: ... print(d) writer.writerow(d) 承诺之后继续链接?

1 个答案:

答案 0 :(得分:1)

您需要使用Promise.all等待所有承诺:

 return keys(cacheStore).then((keys) => { // 1st
    return Promise.all(keys.map((key) => {
        return this.getCachedResponse(key).then((item) => { // 2nd
            if (item.expire < now) {
               return this.deleteCache(key)
            }
        })
    }));
})

使用async / await

可以略微提高可读性
 async invalidateCache() {
   const now = Date.now()

   const keys = await getKeys(cacheStore);

   await Promise.all(keys.map(key => this.expireKey(now, key)));
 }

 async expireKey(time, key) {
     const item = await this.getCachedResponse(key);
     if(item.expire < time) 
        this.deleteCache(key);         
 }