从knex-promise获取价值
我有以下function – 从图书馆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
任何build议我做错了什么? 我是否创build了诺言的callbackfalse?
欣赏你的回复
您不能在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));
你可以在这里做的是做一些在当时的块。
function findById(id) { knex('posts').select().where('id', id).first().then(data => { console.log(data); }).catch((err) => console.log(err)); }
如果你想分开外面的逻辑,你可以传递一个callback函数:
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
函数中缺less一个return语句,没有它, findById
将总是返回undefined
。
以下是带回报的function。
function findById(id) { return knex('posts') .select() .where('id', id) .first() .then(data => { return data }) .catch((err) => console.log(err)); }
另外,您需要在promise中使用findById
本身,以便在调用之前知道该值已经asynchronous解决。
试试这个调用findById
的更高级调用:
const id = 1 service.findById(parseInt(id)) .then((result) => { console.log("Post with " + id + ": " + result); });