When my API calls addSub() which returns a promise, The inner promise is able to return data to outer promise, but the outer is unable to return data to AP while giving the following output.

a+b: 9

addSub data: 9

pro: Promise { 8 }

TypeError: Cannot read property 'then' of undefined

function add(a, b){
  console.log("a+b: ",a+b)
  return new Promise((resolve, reject) => {
    resolve(a+b)
    })
}

function addSub(){
  add(4,5)
    .then((data) => {
        console.log("addSub data: ", data)
        var pro = new Promise((resolve, reject) => {
          resolve(data - 1)
        })
        console.log("pro: ",pro)
        return pro
    })
}

app.get('/promise', function (req, res){
    addSub()
    .then((data) => {
        console.log("final res: ", data)
        res.send({"data": data})
    })
});

2 Answers

3
user11129751 On Best Solutions

You must add a return before add(4,5):

...    
function addSub(){
            return add(4,5)
            .then((data) => {
            ...

function add(a, b){
    console.log("a+b: ",a+b)
    return new Promise((resolve, reject) => {
        resolve(a+b)
    })
}
function addSub(){
    return add(4,5)
    .then((data) => {
        console.log("addSub data: ", data)
        var pro = new Promise((resolve, reject) => {
            resolve(data - 1)
        })
        console.log("pro: ",pro)
        return pro
    })
}

addSub()
  .then((data) => {
      console.log("final res: ", data)
      res.send({"data": data})
  })

0
Vimaciel On

Just put a return statement before call add function inside your addSub function

function addSub() {
    return add(4, 5)
        .then((data) => {
            console.log("addSub data: ", data)
            var pro = new Promise((resolve, reject) => {
                resolve(data - 1)
            })
            console.log("pro: ", pro)
            return pro
        })
}