Javascript Promise.all返回空数组
我有一系列请求,我正试图使用Javascript Promise.all返回空数组,javascript,Javascript,我有一系列请求,我正试图使用Promise.all运行这些请求,但我没有从Promise.all.then()中得到任何回报,不知道为什么 productIdArray.forEach(id => { requests.push(rp('https://******br' + '/****/v2/api/*****/' + parametersString + pessoaId + '&idProduto=' + id)); }); Promise.all(requests)
Promise.all
运行这些请求,但我没有从Promise.all.then()
中得到任何回报,不知道为什么
productIdArray.forEach(id => {
requests.push(rp('https://******br' + '/****/v2/api/*****/' + parametersString + pessoaId + '&idProduto=' + id));
});
Promise.all(requests)
.then((resultados) => resultados.forEach(resultado => {
console.log(resultados)
if (resultado) {
accounts.push({
'idProduto': JSON.parse(resultado).content.idProduto,
'contas': JSON.parse(resultado).content
});
}
})).catch(err => console.log(err));
return accounts;
我错过什么了吗?RP是请求承诺库您需要从外部函数返回承诺。一旦函数的一部分是异步的,整个函数就是异步的 类似这样的东西应该可以解决这个问题(替换
forEach
w/map
)
您确定从
然后
中没有结果,还是从退货账户中没有结果?!对<代码>返回帐户
将出现在Promise.all()之前。然后()
运行resultados.forEach
返回未定义的帐户。另外,您正在另一个productIdArray.forEach
回调中使用Promise.all
。JS不会神奇地暂停外部函数以等待一些内部承诺。如果console.log
在resultados.forEach
内,它怎么能打印空数组@DanielBezerraDeMenezes仍然是对承诺的内在呼唤。所有的都不会暂停你的外在功能<代码>退货账户代码>在resultados.forEach
// using map to create an array of pending requests
const requests = productIdArray.map(id => rp('https://******br' + '/****/v2/api/*****/' + parametersString + pessoaId + '&idProduto=' + id));
// returning a promise
return Promise.all(requests)
.then(resultados => resultados.map(resultado => ({
'idProduto': JSON.parse(resultado).content.idProduto,
'contas': JSON.parse(resultado).content
})).catch(err => console.log(err));