- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有以下功能 - 来自库 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/
这个问题在这里已经有了答案: final keyword in method parameters [duplicate] (9 个回答) 关闭 8 年前。 在此示例中,声明 Object fina
我的目标:是通过我的函数更新字段获取选定值并使用函数输出值运行它。 问题:当我从列表中选择值时,它不会触发函数,也不会更新字段。 感谢您的帮助。 HTML 12 14 16 18 20 22 24
我有一本具有这种形式的字典: myDict = {'foo': bar, 'foobar baz': qux} 现在,我想拆分字典键中的空格,使其成为下一个键并获取值(重复)。 myDictRev1
vector a; vector b; int temp_holder; cout > temp_holder) a.push_back(temp_holder); cout > temp_h
Java 的开发过程中免不了与 Date 类型纠缠,准备总结一下项目经常使用的日期相关操作,JDK 版本 1.7,如果能够帮助大家节约那么几分钟起身活动一下,去泡杯咖啡,便是极好的,嘿嘿。当然,我
我正在使用 jquery ui 日期选择器来获取 fromDate 和 toDate 以下是from日期的代码 $("#from_date").datepicker({
我是一名优秀的程序员,十分优秀!