node中这两种写法哪种方法更合适,为什么?
const result=[1,2,3,4,5,6,7,8]
const data=[]
for(let i=0;i<result.length;i++){
const item=await mysql.query('select name from user_info where id=?',[result[i]])
data.push(item[0].name)
}
和这种
const result=[1,2,3,4,5,6,7,8]
const data=await Promise.all(result.map(async()=>{
const item=await mysql.query('select name from user_info where id=?',[result[i]])
return item[0].name
}))
感觉都不合适吧,是不是改下sql?
select name from user_info where id in result
另外,如果非要一个个的去查,第二个要好些,但是建议封装函数,如下: