【发布时间】:2019-08-13 07:32:36
【问题描述】:
我正在将此代码与快速路由和 nano 一起使用:
router.get('/', function (request, response) {
db.view('designdoc', 'bydate', { 'descending': true })
.then(results => {
// data manipulation of results, all blocking and fine
return results;
})
.then(results => {
nano.uuids(1)
.then(uuids => {
results.uuid = uiids['uuids'][0];
resolve(); // return ?
})
.catch(error => {
// ?
});
});
return results;
})
.then(results => { response.json(results); }) // how to have results.uuid = something from the previous then ?
.catch(error => { response.json(error); });
我想在结果中添加一个来自 nano.uuid 的 uuid,但我不知道如何在下一个 then 中操作承诺。
如何从nano.uuid获取数据,等待并添加到results?
编辑
我正在切换到@narayansharma91 建议的异步方法,这段代码解决了我的问题:
router.get('/', async function (request, response) {
const results = await db.view('designdoc', 'bydate', { 'descending': true });
var uuid = await nano.uuids(1);
results.uuid = uuid.uuids[0];
response.json(results);
}
但我仍然想了解基于承诺的解决方案。
【问题讨论】:
-
性能提示:没有理由依次运行
await db.view和await nano.uuids,可以使用Promise.all获得更好的响应时间:const [results, uuid] = await Promise.all([db.view('designdoc', 'bydate', { 'descending': true }), nano.uuids()])
标签: javascript node.js express promise pouchdb