我是Node的新手,试图理解回调和Promise。我正在使用开放源代码HTTP基准测试模块从特定URL提取数据并在获取数据后处理结果。这是我的代码
'use strict'
const autocannon = require('autocannon')
const instance = autocannon({
url: 'http://localhost:3000',
connections: 5,
duration: 5
}, (err, result) => handleResults(result))
async function handleResults (res){
try{
let abReport = [];
abReport.push(
'Test Completed:' + '\n' +
'Time taken for tests:' + res.duration + '\n' +
'Total Concurrent Connections:' + res.connections + '\n' +
'URL:' + res.url + '\n' +
'Total Errors:' + res.errors + '\n' +
'Total Timeouts:' + res.timeouts + '\n'
)
console.log(abReport.join('\n'));
}
catch(error) {
console.error(error);
}
}
autocanon
会将输出传递到handleResults,但是handleResults出错并显示错误TypeError: Cannot read property 'duration' of undefined
。我正在尝试寻找一种方法,仅在从自动炮成功传递值之后,才能处理handleResults。
答案 0 :(得分:0)
将(err, result) => handleResults(result)
更改为
(err, result) => {
if (err != null) return; // or do some error handling
handleResults(result);
}
答案 1 :(得分:0)
我使用下面的代码来工作:
'use strict'
const autocannon = require('autocannon');
const getAbReport = async () => {
try {
const instance = await autocannon({
url: 'http://localhost:3000',
connections: 5,
duration: 5
}, (err, result) => handleResults(result));
} catch(error) {
console.log(error);
}
}
async function handleResults(result) {
try{
let abReport = [];
abReport.push(
'Test Completed:' + '\n' +
'Time taken for tests:' + result.duration + '\n' +
'Total Concurrent Connections:' + result.connections + '\n' +
'URL:' + result.url + '\n' +
'Total Errors:' + result.errors + '\n' +
'Total Timeouts:' + result.timeouts + '\n'
)
console.log(abReport.join('\n'));
}
catch(error) {
console.error(error);
}
}
getAbReport();
答案 2 :(得分:-1)
使用异步等待,您可以更新代码,
'use strict'
const autocannon = require('autocannon');
async function handleResults (res){
try{
let abReport = [];
abReport.push(
'Test Completed:' + '\n' +
'Time taken for tests:' + res.duration + '\n' +
'Total Concurrent Connections:' + res.connections + '\n' +
'URL:' + res.url + '\n' +
'Total Errors:' + res.errors + '\n' +
'Total Timeouts:' + res.timeouts + '\n'
)
console.log(abReport.join('\n'));
}
catch(error) {
console.error(error);
}
}
const getAbReport = async () => {
try {
const result = await autocannon({
url: 'http://localhost:3000',
connections: 5,
duration: 5,
});
await handleResults(result);
} catch(error) {
console.log(error);
}
}
getAbReport();