Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

forEach遍历数组查询数据库,返回多个Promise,如何接收?

forEach遍历数组查询数据库,返回多个Promise,如何接收?

本人小白,没有系统的学过nodejs和es6,平常也就写个增删改查,面向百度足够了。但是最近在帮同事做一个分析系统的时候,出现了问题。有一个数组每项都是一个对象([{num:500},{num:600}]差不多就是这样),现在需要把这个数组中包含的对象都做为sql查询语句的where条件(“select * from biao where num = ”+item.num),于是就想用forEach来循环这个数组。由于涉及到异步同步的问题,于是就想每次循环return一个Promise对象,再.then(根据本人现在知识水平只想到了这)。那么就有了开篇的问题,每循环查询一次返回一个Promise,如何汇总这些promise,然后对他们进行操作呢?我已经看到其他回答类似的功能是用的Array.map,但是forEach就没有方法吗?

查询数据库函数封装:

 function chaxun (arr){
    var sql = `select * from tb where num = `;
    arr.forEach(function(item,index){
        return new Promise(function(resolve,reject){
            db.query(sql+item.num,row=>{
                resolve(row);
            })
        })
    })
}

async 函数:

cxtb : async function(yishuzu,ershuzu){
    const yires = await chaxun(yishuzu);
    return yires;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 function chaxun (arr){
    var sql = `select * from tb where num = `;
    var temp = []
    arr.forEach(function(item,index){
        temp.push(new Promise(function(resolve,reject){
            db.query(sql+item.num,row=>{
                resolve(row);
            })
        }))
    })
    return temp
}
cxtb : function(yishuzu,ershuzu){
    Promise.all(temp).then(res => { console.log('这样试试看呢?')})
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...