[英]TypeError: Cannot read property 'then' of undefined (Promise) (node.js)
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. 当我的API调用返回承诺的
addSub()
,内部的addSub()
可以将数据返回给外部的addSub()
,但是外部的addSub()
不能将数据返回给AP,同时提供以下输出。
a+b: 9
a + b:9
addSub data: 9
addSub数据:9
pro: Promise { 8 }
赞成:承诺{8}
TypeError: Cannot read property 'then' of undefined
TypeError:无法读取未定义的属性“ then”
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)
: 您必须在
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 只需在addSub函数内的调用add函数之前放一个return语句
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
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.