仅在特定功能完成时如何发送响应。我尝试使用promises,但这似乎没有用。
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});
});
还有其他方法可以解决这个问题吗?
答案 0 :(得分:0)
您使用for
执行多项请求即使您的承诺得到解决,也会解决此问题。
我会这样做:
const myPromises = Promise.all(deals.map(deal => {
return new Promise((resolve, reject) => {
// ... do your request here
// call resolve in the callback request
})
}))
myPromises.then(result => {
// ... here all your requests have been resolved
// call res.status(200).json({...})
})
答案 1 :(得分:0)
如果您切换到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);
});