Как условно отправить асинхронный запрос в качестве предварительного запроса в JavaScript? - PullRequest
0 голосов
/ 05 июня 2018

У меня есть ситуация, что, если условие выполняется, тогда я

  • отправлю requestOne,
  • сделаю что-то с ответом на успех,
  • , тогда яотправит запрос два.

С другой стороны, если условие ложно, я

  • просто отправлю запрос два.

Есть ли лучший метод или лучший / красивый способ сделать это?

Запросы асинхронные , а вот псевдокод:

if (condition) {
    sendRequestOne().then(function (response) {
        // do some stuff
    }).then(function () {
        sendRequestTwo();
    });
} else {
    sendRequestTwo();
}

Ответы [ 2 ]

0 голосов
/ 05 июня 2018

Используя троичный ? оператор , вы можете переходить между 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}
0 голосов
/ 05 июня 2018
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')
 })
}

пример

...