node mysql写法

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
}))
阅读 1.4k
1 个回答

感觉都不合适吧,是不是改下sql?

select name from user_info where id in result

另外,如果非要一个个的去查,第二个要好些,但是建议封装函数,如下:

async function findById(id){
  return await mysql.query('xxxx')
}

let promiseList = result.map(id=>{
  return findById(id);
})

let resLst = await Promise.all(promiseList)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题