我有一个函数调用,该函数依次调用http.get。当直接调用search方法时,我会正确地得到结果,但是当我通过循环调用所有的getAll方法时,我会得到空的或未定义的结果
function search(url, node, notFound) {
return new Promise(function(resolve, reject) {
http.get(url).then(function(data){
var val = 1;
for (var i = 0; i < data.length; i++) {
$searchModal.find(node).append(`<div class="col-xs-12"><label> ${label} ${val}</label></div>`);
var val = val + 1;
for (key in data[i]) {
var index = 1;
if (key == "Udfs") {
$searchModal.find(node).append(`<div class="col-xs-12"><label> ${key} </label></div>`);
for (udfKey in data[i][key]) {
$searchModal.find(node).append(`<div class="col-lg-3" ><div class="input-group"> <span class="input-group-addon" id="key">${udfKey}</span> <input id="accountModelId" type="text" disabled class="form-control" placeholder="" aria-describedby="accountModel" value="${data[i][key][udfKey]}"></div></div>`);
}
}
for (var j = 0; (Array.isArray(data[i][key])) && j < data[i][key].length; j++) {
$searchModal.find(node).append(`<div class="col-xs-12"><label> ${key} ${index}</label></div>`);
var index = index + 1;
for (objKey in data[i][key][j]) {
$searchModal.find(node).append(`<div class="col-lg-3" ><div class="input-group"> <span class="input-group-addon" id="key">${objKey}</span> <input id="accountModelId" type="text" disabled class="form-control" placeholder="" aria-describedby="accountModel" value="${data[i][key][j][objKey]}"></div></div>`);
}
}
if (!Array.isArray(data[i][key]) && !(data[i][key] instanceof Object)) {
$searchModal.find(node).append(`<div class="col-lg-3" ><div class="input-group"> <span class="input-group-addon" id="key">${key}</span> <input id="accountModelId" type="text" disabled class="form-control" placeholder="" aria-describedby="accountModel" value="${data[i][key]}"></div></div>`);
}
}
}
console.log(data);
resolve(data.toString());
if (data.length == 0) {
$searchModal.find(node).append(notFound);
}
}).catch(function err() {
$searchModal.show("modal")
$searchModal.find(node).append(notFound);
});
});
}
function getAll() {
urls = [contactUrl, accountUrl, assestUrl]
nodes = ['#contactData', '#accountData', '#assetData']
list = [$noContacts, $noAccounts, $noAsset]
for (let i = 0; i < urls.length; i++) {
search(urls[i], nodes[i], list[i]);
}
}
需要帮助来处理此问题。谢谢
答案 0 :(得分:2)
两件事:
1)发出请求时,您可能应该处理拒绝。因此,在致电http.get
之后,应该在您的catch块中reject(err)
。
2)之所以没有得到回应,是因为您没有等待回应。您正在遍历数据集并发出请求,然后您的代码就一直在继续。您要做的是等待所有请求完成,然后再执行一些操作。这是使用es6 all()
库中的Promise
函数的示例。
function getAll() {
urls = [contactUrl, accountUrl, assestUrl]
nodes = ['#contactData', '#accountData', '#assetData']
list = [$noContacts, $noAccounts, $noAsset]
var promiseArray = [];
for (let i = 0; i < urls.length; i++) {
promiseArray.push(search(urls[i], nodes[i], list[i]));
}
Promise.all(promiseArray)
.then((resp) => {
console.log(resp[0]); // response from 1st request
console.log(resp[1]); // response from 2nd request
}).catch((err) => {
console.log(err);
})
}