我正在寻找一种获取数据的方法,下面是代码。
// 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/await和http://bookshelfjs.org/
答案 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"
});
});