等待嵌套承诺以最里面的多个请求结束



在最外层的 for循环迭代数组中,这个数组更具体地说是一个对象列表,其中每个对象都包含一个数组,其中包含我需要使用的代码,以便访问外部 API 提供的一些信息(为了简单起见,我使用了模型对象(:

data = [ {resultOfRequest, [code1,code2,code3] } , {resultOfRequest, [代码 4,代码 5,代码 6] }, ... }

我需要遍历数据数组,为每个codeX发出一个请求并将结果存储在resultOfRequest上。

在顺序范式上,它将是这样的:

for all items in data as work: 
for all items in work as codeArray:
for all codes in codeArray as code:
work.result = request(to-api, code) //waiting here for termination

我开始使用javascript几天,我读到它的意思是非阻塞的,但是对于这个特定的任务,我必须使其同步并等到所有对象都被检查过。

我的尝试涉及承诺,看起来像这样:

//here the map iterates over the data array
// work = {resultOfRequest, [code1,code2,code3] }
Promise.all(data.map((work, index) => {
orclass.elserec(work, 0).then((results) => {
console.log(results);
});
}))
.then(results => {
console.log("finished")
});

由于我需要在索引 3 到达时结束递归调用,因此我必须在回调时执行此操作:

// here i try to iterate through the codeX arrays, and making requests 
//(where work =  {resultOfRequest,  [code1, code2, code3]})
elserec: function(work, i){
return request('api-url-code= work.array[i]', function(error, response, body) {
result = JSON.stringify(JSON.parse(body));
if (!error && response.statusCode == 200 && i !== 3) {
console.log(result);
work.resultOfRequest.push(result);
return orclass.elserec(work, i+1);
} else {            
return result;
}
});
}

它卡在数据的第三个请求[0] 处。

我宁愿只使用回调,只是为了掌握它们的工作原理,因为我从未使用过 javascript,宁愿先使用承诺之前的内容来学习(在这个更具体的上下文中,我知道简单异步上下文中的回调并没有什么特别的(!

我找到了一种方法来做到这一点。

递归调用不是一个好主意,所以我用代码([code1, code2,code3](将一个函数(带有请求承诺(映射到数组,最终得到[elrec(code1(,elrec(code2(,elrec(code3(]。之后,我调用 promise.all 与数组上的 promise。它的工作原理是:

Promise.all(data.map((works, index) => {
return Promise.all(works.map((work, index) => {
var promises = work.scopus.map(function(obj){
return orclass.elrec(work,obj).then(function(results){
console.log("working!!!!!!");
})
})
return Promise.all(promises);
}))
})).then(function(){ //all api calls are done, proceed here})

ELREC 函数:

elrec: function(work, code) {
return request('https://api.*****' + code + '*****',
function(error, response, body) {
if (!error && response.statusCode == 200) {
result = JSON.stringify(JSON.parse(body));
work.elsev.push(result);
} else if (response.statusCode == 404) {
work.elsev.push("failed req");
}
});
}

正如我所愿,我可以等待所有承诺"实现"(所有 API 请求都已完成,对于所有代码(,然后采取行动。

最新更新