如何使用Bookshelf js使用await从数据库中获取数据?

时间:2018-09-17 13:22:35

标签: node.js promise bookshelf.js

我正在寻找一种获取数据的方法,下面是代码。

// Await this set of things
    var getResponse = await('pr', 'chat');
    let promise = new Promise((resolve, reject) => {
        resolve("done!");
    });

let chat = new Promise( (resolve, reject) => {
    User
    .where('id', req.body.application_id)
    .fetch({withRelated: ['company']})
    .then(function(result, err) {
        resolve(result);
    });
});

getResponse.keep('pr', promise);
getResponse.keep('chat', chat);


getResponse.then(function(response) {

    console.log('in to reponse:-', response);

    res.status(200).send(response);

},function(err) {

  res.status(400).json({'error' : "Error while fetching data"});
});

在控制台上获得响应的{ pr: Promise { 'done!' }, chat: Promise { <pending> } }

在浏览器上的响应

{
    "pr": {},
    "chat": {}
}

使用https://www.npmjs.com/package/awaithttp://bookshelfjs.org/

1 个答案:

答案 0 :(得分:2)

通过使用本机Promise.all()函数,您可以避免使用额外的库,下面的示例可能会对您有所帮助

let promise = new Promise((resolve, reject) => {
    resolve("done!");
});

//User.where().fetch() return a promise
let chat = User
    .where('id', req.body.application_id)
    .fetch({
        withRelated: ['company']
    });


Promise.all([promise, chat])
    .then(function (response) {
        var data = {
            promise: response[0],
            chat: response[1]
        }

        console.log('in to reponse:-', response);

        res.status(200).send(data);

    })
    .catch(function (err) {
        res.status(400).json({
            'error': "Error while fetching data"
        });
    });