[英]function not returning JSON property value - node.js
我在 Couch.db 上创建了一个数据库,我正在使用 couch.GET 方法来检索文档数据。 我创建了一个测试函数,它将检索“名称”对象的值并通过 console.log 输出结果。
function sendDB() {
couch.get(dbName, viewUrl).then(
function(data, headers, status){
console.log(data.data.rows[0].value.name);
}
)
}
sendDB();
在上面的函数中,输出应该是“John Doe”。 当我尝试返回data.data.rows[0].value.name
的值时出现问题
function sendDB() {
couch.get(dbName, viewUrl).then(
function(data, headers, status){
DB = JSON.stringify(data.data.rows[0].value.name);
return DB;
}
)
}
console.log(sendDB());
在上面的函数中,控制台显示“未定义”,我很困惑。 我需要在其他函数中使用返回值,所以任何帮助将不胜感激。 谢谢
您需要从sendDB()
返回承诺。 目前没有return
到外部函数。
由于承诺是异步的,您需要使用then()
链接到函数调用
function sendDB() {
// return the promise
return couch.get(dbName, viewUrl).then(
function(data, headers, status){
DB = JSON.stringify(data.data.rows[0].value.name);
return DB;
}
)
}
sendDB().then(function(DB){
console.log(DB);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.