我的节点后端有一个端点,在这个端点中,我需要从本地数据库中检索Adhoc集合中的每一项的_id以及一个Numer值,我需要从对象数组中的request()函数体中计算出该值。对象将如下所示
{id: "id", sum: 3}为此,我需要使用for循环遍历Adhocs,并请求每个Adhocs来获得sum值,并且我需要能够在获得所有值之前存储这些值,并将数组res.send()到前端。我在变量中存储sum值时遇到问题。我已经在下面提供了请求的代码。
let theSum = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(
'Response: ' + response.statusCode + ' ' + response.statusMessage
);
let bodyy = JSON.parse(body);
let sum = bodyy.fields.timetracking.originalEstimateSeconds / 3600 * theRate;
return sum;
});我知道这是错误的,因为return语句是针对请求函数中的函数的,所以它不会将sum返回给我的变量。添加另一个回调函数基本上是相同的场景。谁有什么建议,我可以存储请求函数的值,以便我可以进行进一步的调用?
发布于 2019-11-29 20:59:54
你可以使用async和await以及request-promise-native来遍历你的对象并得到你想要的结果列表。
您可以在express.get( )中调用readEstimates函数。只要处理程序是异步的(或者您可以使用readEstimates().then(..))。
现在,我们将在readEstimates调用周围包装一个错误处理程序,因为这可能会抛出错误。
例如:
const rp = require('request-promise-native');
async function readEstimates() {
const sumList = [];
for(const adhoc of adhocList) {
// Set your options here, e.g. url for each request.. by setting json to true we don't need to JSON.parse the body.
let options = { url: SOME_URL, json: true, resolveWithFullResponse: true };
let response = await rp(options);
console.log('Response: ' + response.statusCode + ' ' + response.statusMessage);
const sum = response.body.fields.timetracking.originalEstimateSeconds / 3600 * theRate;
sumList.push(sum);
}
return sumList;
}
async function testReadEstimates() {
try {
const sumList = await readEstimates();
console.log("Sumlist:", sumList);
} catch (error) {
console.error("testReadEstimates: An error has occurred:", error);
}
}
testReadEstimates();您还可以在快速路由中使用readEstimates:
app.get('/', async (req, res) => {
try {
const sumList = await readEstimates();
res.json({sumList}); // Send the list to the client.
} catch (error) {
console.error("/: An error has occurred:", error);
res.status(500).send("an error has occurred");
}
})https://stackoverflow.com/questions/59104137
复制相似问题