请问这样的逻辑我要怎么用Promise(bluebird)写呢?
发布于 8 年前 作者 SiriusGuo 3810 次浏览 来自 问答

我在最外面弄了一个对象,用于最终的输出。 var data = {};

然后逻辑是这样的:

  1. mysql查询一条数据,return一个实体;
  2. 根据查到的实体,mysql查询一堆数据,return这堆数据;
  3. 根据查询到这堆数据,每条数据再去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 回复

@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 => { // 错误处理 })

自己简单封装个就行了。

	static wrapCallback(...args){
		let root = args.shift()
		let func_path = args.shift()
		let func = _.get(root,func_path)
        let err = ""
		if(typeof func != "function"){
			err = new Error(func_path + " is not function")
		}
        let log = (this.req && this.req.log) || (this.log && this.log.bind(this))  || console.log
        log("wrapFunc",root.name + "." + func_path, err && err.toString())
        if(err){
            throw err
        }		
		return new Promise((resolve,reject) => {
			let next = (err,data) => {
				if(err){
					reject(err)
					return
				}
				resolve(data)
			}
			func.apply(this,args.concat(next))
		})
	}

调用:

await wrapCallback(Fs,"exists",src).catch((e) => exists = e)

then 的写法还有会有嵌套问题的,用 async await 吧。

@285858315 @429365799 开眼界了,我刚学Node不久,向二位大神多多学习!非常感谢!

回到顶部