如何从第一个承诺列表构造第二个承诺列表并进行迭代



我有一个类别列表。我需要查看数据库中是否有可用的类别ID,如果是,则将这些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.protype.then((实际上返回了一个Promise

我希望这能有所帮助!

最新更新