Javascript 从knex承诺中获得价值

Javascript 从knex承诺中获得价值,javascript,node.js,Javascript,Node.js,我有以下函数-来自库knex-返回一个承诺: function findById(id) { knex('posts').select().where('id', id).first().then(data => { return data }).catch((err) => console.log(err)); } const id = 1 console.log("Post with " + id + ": " + service

我有以下函数-来自库knex-返回一个承诺:

function findById(id) {
    knex('posts').select().where('id', id).first().then(data => {
        return data
    }).catch((err) => console.log(err));
}

const id = 1
        console.log("Post with " + id + ": " + service.findById(parseInt(id)))
但是,我收到以下错误消息:

Post with 1: undefined
ReferenceError: id is not defined
有什么建议我做错了什么?我是否创建了虚假承诺的回调


感谢您的回复

您不能在javascript的
promise
中返回值

为什么?

因为
promise
是异步的

因此,程序的执行顺序是

console.log("Post with " + id + ": " + undefined) //Because promise haven't return value yet
knex('posts').select().where('id', id).first().then(data => {
        return data
    }).catch((err) => console.log(err));
你能做的就是在then街区做点什么

function findById(id) {
    knex('posts').select().where('id', id).first().then(data => {
        console.log(data);
    }).catch((err) => console.log(err));
}
如果要分离外部逻辑,可以传递回调函数:

function findById(id, callback) {
    knex('posts').select().where('id', id).first().then(data => {
        callback(data)
    }).catch((err) => console.log(err));
}

const id = 1
service.findById(parseInt(id), (data)=>{
    console.log(data);
})

我认为这里有两个问题

首先,您的
findById
函数缺少一个return语句,如果没有它,
findById
将始终返回
undefined

下面是带返回的函数

function findById(id) {
    return knex('posts')
         .select()
         .where('id', id)
         .first()
         .then(data => {
            return data
         })
        .catch((err) => console.log(err));
}
此外,还需要在promise中使用
findById
本身,以便在调用该值之前知道该值已异步解析

对于调用
findById
的更高级别调用,请尝试以下操作:

const id = 1
service.findById(parseInt(id))
    .then((result) => {
      console.log("Post with " + id + ": " + result);
    });