使用Promise.all()进行3次in查询

来源:10-4 in查询避免循环查询数据库

慕用3271571

2020-08-12

由于三条in查询并没有顺序要求,我们这里用Promise.all()做parallel query而不是sequential query是不是更好些

const arts = []
for (let key in artInfoObj) {
    const ids = artInfoObj[key]
    if (ids.length === 0) {
        continue
    }

    key = parseInt(key)
    arts.push(await Art._getListByType(ids, key))
}

return flatten(arts)

代码如下

const arts = [];
for (let key in artInfoObj) {
  const ids = artInfoObj[key];
  if (ids.length !== 0) {
    key = parseInt(key);
    arts.push(Art._getListByType(ids, key));
  }
}
const result = await Promise.all(arts);

return flatten(result);
写回答

1回答

7七月

2020-08-12

前端PromiseAll也是发若干请求,然后等待3条结束后再回调吧?这个和后端查询有什么关系?

0
2
慕用3271571
老师你for loop里的代码转换一下应该是 await Art._getListByType(ids, 100); await Art._getListByType(ids, 200); await Art._getListByType(ids, 300); 他们是同步的 使用Promise.all()的代码转换一下应该是 const promise1 = Art._getListByType(ids, 100); const promise2 = Art._getListByType(ids, 200); const promise3 = Art._getListByType(ids, 300); await(promise1); await(promise2); await(promise3); 他们是异步的 不过Promise.all()同时具备fail fast的特性,任何一个promise如果被reject了,剩下的promise都不会被执行了
2020-08-12
共2条回复

Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》

理解异步编程本质/培养面向对象思维,独立完成Node.js服务端开发

2223 学习 · 878 问题

查看课程