假设 Bluebird,利用库功能并删除嵌套:
var api = Promise.promisifyAll({method1:method1,method2:method2:method3:method3});
api.method1Async(req.params.param).then(function(res){
return [method2Async(res),{model:res}];
}).spread(function(res,result){
result.models = res;
if(models.length > 0){
return method3Async(mode,res).then(function(res){
result.models2 = res;
}).return(result);
}
return results;
}).then(function(results){
res.render("index.html",results);
}).catch(next); // also handle render errors
或者,您可以执行类似嵌套更少的操作:
var api = Promise.promisifyAll({method1:method1,method2:method2:method3:method3});
var p1 = api.method1Async(req.params.param);
var p2 = p1.then(api.method2Async);
var p3 = p2.then(function(models){
if(models.length > 0) return api.method3Async(mode,models);
});
Promise.all([p1,p2,p3]).spread(function(r1,r2,r3){
var results = {model:r1,models:r2};
if(models.length > 0) results.models2 = r3;
res.render("index.html",results);
}).catch(next)
或者,您可以使用 Bluebird 协程(需要 --harmony-generators 标志)
var api = Promise.promisifyAll({method1:method1,method2:method2:method3:method3});
Promise.coroutine(function*(){
var model = yield method1Async(req.params.param);
var models = yield method2Async(model);
if(models.length > 0){
var models2 = yield method3Async(mode,models);
}
res.render("index.html",{model:model,models:models,models2:models2});
})().catch(next); // should probably extract to a clear method rather than self invoke