The problem of promise Multi-line Writing

 fn1().then(function(res){
    console.log(res)
    return fn2(res).then(function(res){
         console.log(res)
    },function(err){
        console.log(err)
    })
}).catch(function(res){
    return fn3(res).then(function(res){
    console.log(res)
    },function(err){
        console.log(err)
    })
})

fn1 executes and takes different routes according to the returned result. If return fn2, fails, return fn3, seems to start to nest again. Is there a better way to write it?

Mar.10,2021

you can try to change the parameters

function p(bool, msg) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (bool) resolve(msg);
      else reject(msg);
    }, 1000)
  })
}

p(true, 'true').then(function (res) {
  console.log(res);
  return p(true, 'then');
}).catch(function (res) {
  console.log(res);
  return p(true, 'catch');
}).then(function (res) {
  console.log(res);
}).catch(function (res) {
  console.log(res)
})

if you have babel, go to async/await. If not,
is at most more comfortable to split into subfunctions.

Menu