我有一个类别列表。我需要查看类别ID在数据库中是否可用(如果将其插入到另一个表中)
我有两个承诺清单。我想要的是在第一个完成迭代后调用第二个承诺列表

// category ids as follows
let categoryIds = [['cat1','cat2', 'cat3'],['cat4','cat5', 'cat6']];

// insert promise
let insertCategoriesPromiseList = [];

// then iterate through the array and get categories from db

categoryIds.filter((categories) => {

   let isCategoryAvailablePromises = [];

   categories.filter((catId) => {
      isCategoryAvailablePromises.push(checkForCategory(catId));
   })

   Promise.all(isCategoryAvailablePromises)
    .then(data => {
      // if all the cat ids are in the db then insert those cat ids
      // into another table
      insertCategoriesPromiseList.push(insertCatIds(data.cat1, data.cat2, data.cat3))
    })

});

function checkForCategory(catId){
   const promise = new Promise((resolve, reject)=> {
     db.any('select categoryName from category where ...')
      .then(data=>{
         // if all the categories are available return
         resolve(data);
      })
      .catch(e => {
         reject(e);
      })
   })
   return promise;
}

function insertCatIds(catId1, catId2, catId3){
   const promise = new Promise((resolve, reject)=> {
     db.one('insert into products ...')
      .then(data=>{
         // if all the categories are available return
         resolve(data);
      })
      .catch(e => {
         reject(e);
      })
   })
   return promise;
}


我想在创建完整的insertCategoriesPromiseList之后执行以下操作...

Promise.all(insertCategoriesPromiseList)
 .then(p => {

 })
 .catch()

最佳答案

我会这样重写它:

function checkForCategory(catId){
     return db.any('select categoryName from category where ...')
      .then(data=>{
         //massage data if needed
         return data;//return cat id!
      });
}

function insertCatIds(catId1, catId2, catId3){
     return db.one('insert into products ...')
      .then(data=>{
         //massage data if needed
         return data;
      });
}

let load = ['catid1', 'catid2'].map(id => checkForCategory(id));
Promise.all(load).then((...ids) => insertCatIds.apply(this, ids));


注意,我没有写new Promise((resolve, reject) => ...,因为Promise.prototype.then()实际上返回了Promise

我希望这有帮助!

关于javascript - 如何从第一个 promise 列表构造第二个 promise 列表并进行迭代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53094732/

10-09 17:19
查看更多