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})
})
});
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}) })
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
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.