gpt4 book ai didi

javascript - 从 knex-promise 中获取值(value)

转载 作者:搜寻专家 更新时间:2023-10-31 23:51:19 24 4
gpt4 key购买 nike

我有以下功能 - 来自库 knex - 返回一个 promise :

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

对我做错了什么有什么建议吗?我是否创建了 promise false 的回调?

感谢您的回复

最佳答案

您不能在 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 block 中做一些事情。

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);
})

关于javascript - 从 knex-promise 中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com