【发布时间】:2016-05-27 13:37:42
【问题描述】:
我不是 Javascript 专家,我无法理解如何处理一些 Js 特殊性。
我想进行自动化测试,我做了它,它可以工作。 算法很简单:
[for each] test [do] request() [then] testRequest().
function requestFunction(url, KeyWord, path, expected){
request( url + path + '/', function (error, response, body) {
if (!error && response.statusCode == expected) {
msgSuccess("["+KeyWord + "] :\t\tok\t(" + expected + ')' );
}else{
msgError("["+KeyWord + "]\t\tERROR => " + error);
msgError("Error result: \n" + body);
}
});
但是我想从请求中拆分出测试部分,并用 promise 管理它:
var promise1 = new Promise(requestFunction(url, KeyWord, path, expected));
var promise2 = new Promise(testRequest(error, response, body, expected));
Promise.all([promise1, promise2]).then(
console.log(KeyWord + " ok"),
showOnlyTheError(allErrors));
但我不知道如何获取并提供 testRequestResult() 参数(错误、响应、正文)
另一点是我很确定所有的拒绝都将被连接并且结果将自动转到 allErrors 变量。
eg: testRequest(...){ reject("[Error]" + **ErrorNumbers** + ", ")};
最后会显示"1, 2, 3,"。
但我无法解释为什么,尤其是如何解释?
提前致谢。
[编辑] 我试过了:
var arrayOfPaths= [
'Ping',
'PING'];
var promises = arrayOfPaths.forEach(function(path){
return new Promise(resolve => {
msgStatus(url+path+'/');
return resolve(request(url+path+'/'));
});
});
Promise.all(promises).then(
function(result){
//after all promises resolve do something with array of results
msgStatus("result " + result.body );
}
).catch(function(result){
//if any of the promises fail they will be handled here
//do something with errors
msgError("err " + result.error );
}
);
=> 但它总是在 catch 部分出现此错误:
错误未定义
我的服务器收到一个好的请求并返回一个正常的响应(statusCode = 200)
【问题讨论】:
标签: node.js testing request es6-promise