请问这样的逻辑我要怎么用Promise(bluebird)写呢?
发布于 9 年前 作者 SiriusGuo 4564 次预览 最后一次回复是 9 年前 来自 问答
我在最外面弄了一个对象,用于最终的输出。 var data = {};
然后逻辑是这样的:
- mysql查询一条数据,return一个实体;
- 根据查到的实体,mysql查询一堆数据,return这堆数据;
- 根据查询到这堆数据,每条数据再去mysql查询一堆数据,return这堆数据;
然后我写成这样就写不下去了: var data = {}; test.queryEntityAsync(id) //查询实体 .then(function(entity){ data.entity = entity; return test.queryItems(entity.prop1);//根据实体查询一堆数据 }) .then(function(items){ data.entity.items = items; …然后需要把这堆数据里的每条都进行mysql查询,最后再输出这个json,这里用Promise要怎么写呢? })
7 回复
用Promise.all()来做吧,https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
@429365799 谢谢,我最后这样写的: var data = {}; test.queryEntityAsync(id) //查询实体 .then(function(entity){ data.entity = entity; return test.queryItems(entity.prop1);//根据实体查询一堆数据 }) .then(function(items){ data.entity.items = items; var asyncFuncs = []; data.entity.items.forEach(function(item){ asyncFuncs.push(test.mysqlQueryAsync(item.id)); }) Promise.all(asyncFuncs).then(function(){ //…result process… return data; }) })
非常感谢,确实实现了我的业务逻辑。只不过美中不足的是多了一层hell。不知道是不是有更好的解决方案。
var data = {}; test.queryEntityAsync(id) //查询实体 .then(function(entity){ data.entity = entity; return test.queryItems(entity.prop1);//根据实体查询一堆数据 }) .then(function(items){ data.entity.items = items; var asyncFuncs = []; data.entity.items.forEach(function(item){ asyncFuncs.push(test.mysqlQueryAsync(item.id)); }) return Promise.all(asyncFuncs); }) .then(result => { // … }) .catch(err => { // 错误处理 })
自己简单封装个就行了。
调用:
then 的写法还有会有嵌套问题的,用 async await 吧。
@285858315 天了噜
@285858315 @429365799 开眼界了,我刚学Node不久,向二位大神多多学习!非常感谢!