node.js - 如何使用 Promise 仅在功能完成时发送响应
问题描述
如何仅在特定功能完成时发送响应。我尝试为此使用承诺,但这似乎不起作用。
let dealPromise = new Promise(function(resolve, reject){
for (let i = 0;i < deals.length;i++) {
let link = 'https://api.cortellis.com/api-ws/ws/rs/deals-v2/deal/' + deals[i] + '?fmt=json';
let options = {
method: 'GET',
uri: link,
auth: auth,
};
let constant = constants.collection('clarivate');
request(options, function(error, response, body) {
body = JSON.parse(body).dealRecordOutput;
if (body.length === 0) {
res.status(204).json({'data': []});
next();
}
else {
let type = body.Type;
type_list.push(type);
let status_val = body.Status;
status_list.push(status_val);
resp['type'] = type_list;
resp['status'] = status_list;
}
});
}
resolve(resp);
});
dealPromise.then(function (result) {
res.status(200).json({'data': result});
});
还有其他方法可以解决这个问题吗?
解决方案
如果您切换到request-promise
库来执行您的请求,那么它将为每个请求返回一个承诺,然后您可以使用Promise.all()
它们来知道它们何时完成。
您的代码在许多主题上有点不完整,例如遇到空主体时该怎么办以及您希望如何构建最终result
数据。因此,允许您填写这些详细信息,这里有一个适合您的通用结构:
const rp = require('request-promise');
let type_list = [], status_list = [];
Promise.all(deals.map(item => {
let options = {
method: 'GET',
uri: 'https://api.cortellis.com/api-ws/ws/rs/deals-v2/deal/' + item + '?fmt=json',
auth: auth
};
let constant = constants.collection('clarivate');
return rp(options).then(body => {
if (body.length !== 0) {
try {
let data = JSON.parse(body).dealRecordOutput;
type_list.push(data.Type);
status_list.push(data.Status)
} catch(e) {
// log and skip items with bad JSON
console.log(e);
}
}
});
})).then(() => {
// all requests done here
let result = {};
// put code here to create result using type_list and status_list
res.status(200).json({data: result});
}).catch(err => {
// got an error in one of the requests
console.log(err);
res.sendStatus(500);
});
推荐阅读
- javascript - 将一个特定的对象道具从一个数组移动到另一个对象数组,如果条件(JavaScript ES6)
- python - 在 Amazon Linux 中安装 pymol-open-source 时 Python 版本上的 miniconda UnsatisfiableError
- excel - Excel Power Query 检查大型数据集中的重复项
- arrays - C 练习布尔型分段错误
- c - 重置 EOF 以读取 .dat 文件?
- python - 使用 Dockerfile 中的 ENTRYPOINT 标记和 docker-compose
- angular - Angular 自定义属性指令无法正常工作
- javascript - React Native Expo:组件异常
- java - java - 如何从Java中的运行时执行中获取实时输出?
- php - 正在显示我的表头,但没有从数据库中获取数据