我有一种情况,如果条件成立,那么我将
另一方面,如果条件为假,我将
是否有最佳做法或更好/更美妙的方式?
请求是 async ,这里是伪代码:
if (condition) {
sendRequestOne().then(function (response) {
// do some stuff
}).then(function () {
sendRequestTwo();
});
} else {
sendRequestTwo();
}
答案 0 :(得分:1)
使用ternary ?
operator,您可以在sendRequestOne()
和Promise.resolve()
之间进行分支。
(condition ? sendRequestOne() : Promise.resolve()).then(sendRequestTwo)
const sleep = ms =>
new Promise(resolve => { setTimeout(resolve, ms, ms) })
const labeled = label => async () => {
console.log(label)
console.log(`slept ${await sleep(1000) / 1000}s`)
}
const sendRequestOne = labeled('one')
const sendRequestTwo = labeled('two')
const demo = condition =>
(condition ? sendRequestOne() : Promise.resolve()).then(sendRequestTwo)
;(async () => {
console.log('condition: false')
await demo(false)
console.log('done')
await sleep(2000)
console.log('condition: true')
await demo(true)
console.log('done')
})()
.as-console-wrapper{max-height:100%!important}
答案 1 :(得分:0)
function call1(str , cb){ console.log(str); cb();}
function call2(str , cb){ console.log(str); cb();}
let flag= true;
if(flag){
call1('call1',function(){
call2('call2',function(){
console.log('done')
})
})
}else{
call2('call2',function(){
console.log('done')
})
}