gpt4 book ai didi

javascript - 如何将回调 hell 转化为 promise ?

转载 作者:行者123 更新时间:2023-11-30 10:16:24 24 4
gpt4 key购买 nike

考虑到这个例子:

app.get('/url/:param', function(req, res, next) {
var param = req.params.param;
method1(param, function(err, model) {
if(err) return next(err);
method2(model, function(err, models) {
if(err) return next(err);
if(models.length > 0) {
method3(mode, models, function(err, models2) {
res.render("index.html", {model: model, models: models, models2: models2});
});
} else {
res.render("index.html", {model: model, models: models});
}
});
});
}

有没有办法使用 promises 来简化这个例子?看看所有的方法都是依赖的,并且有像 if(models.length > 0) 这样的验证此外,我需要将 res.render 分组到一个独特的地方。

最佳答案

假设是 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

关于javascript - 如何将回调 hell 转化为 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23461082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com