我正在尝试了解knex
并为其创建了以下示例服务层:
const config = require('../db/knexfile');
const env = 'development';
const knex = require('knex')(config[env]);
/**
* Return all posts
*/
function getAllPosts() {
return knex('posts').select().then(data => {
return data
})
}
/**
* Create a post
*/
function create(title, description) {
console.log("Titel: " + title + " Description: " + description)
return knex('posts')
.insert({
title: title,
description: description,
deleted: true,
createdAt: new Date(),
updatedAt: new Date()
}, 'id')
.then(id => {
console.log("Inserted post with id "+ id)
return id;
})
.catch((err) => console.log(err));
}
/**
* find a post by id
*/
function findById(id) {
try {
return knex('posts').select().where('id', id).first().then(data => {
return data
})
} catch (e) {
console.log(e)
}
}
module.exports = {
create,
getAllPosts,
findById
}
我从另一个文件调用上述文件:
const service = require('./t5_0-serviceLayer')
async function main() {
//prepare data
//service.prepareData()
//getAll
service.getAllPosts().then(data => {
console.log(JSON.stringify(data))
})
//create
const id = service.create("Test post", "Test description")
console.log("Post with " + id + ": " + service.findById(id))
//get all Posts
const res = service.getAllPosts()
console.log("We have " + res.length + " posts.")
}
main().then().catch(err => console.error(err))
我得到以下输出:
Titel: Test post Description: Test description
Post with undefined undefined
We have undefined posts.
[{"id":43,"title":"Et saepe qui occaecati unde nesciunt et.","description":"Sint commodi possimus sunt voluptatibus rerum. Incidunt mollitia accusantium ita
que nihil tempora. Qui veritatis ipsam expedita velit aut consequatur distinctio. Veritatis culpa labore rem ut a non perferendis.","deleted":false,"created
At":"2017-09-17T03:18:19.452Z","updatedAt":"2017-09-17T06:29:40.385Z","deletedAt":"2017-09-17T08:05:17.367Z"},{"id":44,"title":"Deserunt laborum reiciendis
magnam doloremque animi aspernatur sunt quod.","description":"Ea recusandae voluptas magni magni ipsum non dolorem iusto modi. Ipsum fuga inventore corporis
qui. Qui voluptatum eaque nesciunt expedita sed ipsa vel dolor inventore. Quos praesentium dolorum aut et amet amet tempora sed et.","deleted":true,"create
dAt":"2017-09-16T22:23:51.956Z","updatedAt":"2017-09-17T13:46:44.679Z","deletedAt":"2017-09-17T11:09:14.936Z"},{"id":45,"title":"Quibusdam sunt qui beatae."
,"description":"Aut tempore totam. Nihil qui est rerum ut ipsum at autem sint. Pariatur tempore praesentium. Magnam doloremque ipsam. Nihil nesciunt odit bl
anditiis.","deleted":false,"createdAt":"2017-09-16T20:58:03.889Z","updatedAt":"2017-09-17T11:19:06.696Z","deletedAt":"2017-09-17T03:42:25.541Z"},{"id":46,"t
itle":"Test post","description":"Test description","deleted":true,"createdAt":"2017-09-17T17:34:12.882Z","updatedAt":"2017-09-17T17:34:12.882Z","deletedAt":
null},{"id":47,"title":"Test post","description":"Test description","deleted":true,"createdAt":"2017-09-17T17:35:54.056Z","updatedAt":"2017-09-17T17:35:54.0
56Z","deletedAt":null},{"id":48,"title":"Test post","description":"Test description","deleted":true,"createdAt":"2017-09-17T17:36:28.801Z","updatedAt":"2017
-09-17T17:36:28.801Z","deletedAt":null}]
Unhandled rejection Error: Undefined binding(s) detected when compiling FIRST query: select * from "posts" where "id" = ? limit ?
at QueryCompiler_PG.toSQL (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\knex\lib\query\compiler.js:131:13)
at Builder.toSQL (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\knex\lib\query\builder.js:115:44)
at C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\knex\lib\runner.js:56:32
at tryCatcher (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\util.js:16:23)
at C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\using.js:185:26
at tryCatcher (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:693:18)
at Promise._fulfill (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:638:18)
at PromiseArray._resolve (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise_array.js:126:19)
at PromiseArray._promiseFulfilled (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise_array.js:144:14)
at Promise._settlePromise (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:574:26)
at Promise._settlePromise0 (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (C:\Users\user\Desktop\Coding Projects\learning_knex\node_modules\bluebird\js\release\promise.js:693:18)
Inserted post with id 49
我目前在服务层
方面遇到以下问题const id = service.create("Test post", "Test description")
service.getAllPosts()
有什么建议我做错了吗?
答案 0 :(得分:1)
您的async
功能似乎正在使用main
。您需要在await
内的每个promise返回函数调用之前放置main
。我假设service.create
返回一个承诺?如果是,请使用以下内容:
const id = await service.create("Test post", "Test description")
同样适用于service.getAllPosts
:
const res = await service.getAllPosts()
@trincot的答案没有错......它只是忽略了你试图使用async
的事实,这是现代节点版本的可用语言功能。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
请记住,您可能希望在try/catch
块中执行此操作以处理任何意外错误。
答案 1 :(得分:0)
service.getAllPosts()
返回一个承诺,而不是承诺的值。所以这不是你显然期待的数组。
您需要继续使用then
来访问仅以异步方式提供的结果:
service.getAllPosts().then(function(res) {
console.log("We have " + res.length + " posts.");
});