简体   繁体   中英

Promise - return data to constant with async / await function

I am trying to understand knex and have created the following example service layer for it:

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
}

I am calling the above file from another file:

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

I get the following output:

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

I am currently having the following problems with my service layer

  • I am not getting the id of the created post back when I call const id = service.create("Test post", "Test description")
  • I do not get the post length back when I call service.getAllPosts()

Any suggestion what I am doing wrong?

It looks like you're using async on your main function. You need to put await before each promise returning function call within main . I'm assuming service.create returns a promise? If it does, then use something like this:

const id = await service.create("Test post", "Test description")

Same goes for service.getAllPosts :

const res = await service.getAllPosts()

@trincot's answer isn't wrong... it just ignores the fact that you're attempting to use async , which is an available language feature on modern node versions. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Keep in mind that you probably want to do that in a try/catch block to handle any unexpected errors.

service.getAllPosts() returns a promise, not the promised value. So it is not the array you were apparently expecting.

You need to keep using then to get access to the result that will only be available asynchronously:

service.getAllPosts().then(function(res) {
    console.log("We have " + res.length  + " posts.");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM