So I have a promise which contains multiple checks like this
function test(){
var deferred = q.defer()
var passed = false
if(!passed){
deferred.reject("Don't proceed")
//return
} else {
if(!passed){
deferred.reject("Don't proceed")
} else {
if(!passed){
deferred.reject("Don't proceed")
} else {
setTimeout(function(){
console.log("Hello");
deferred.resolve()
}, 100);
}
}
}
return deferred.promise
}
This looks bad because there is a pyramid at the bottom. I'm wondering is there something like return in 'q' which can make the code look better? For example like this:
function test(){
var deferred = q.defer()
var passed = false
if(!passed){
deferred.reject("Don't proceed")
return
}
if(!passed){
deferred.reject("Don't proceed")
return
}
if(!passed){
deferred.reject("Don't proceed")
return
}
setTimeout(function(){
console.log("Hello");
deferred.resolve()
}, 100);
return deferred.promise
}
This definitely doesn't work because it returned before promise is returned, but I'm wondering is there something like a return?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…