我有一个承诺调用另一个承诺,但我不知道如何访问我试图存储所有承诺的变量memberContractInfo
。在下面的代码中,我有两个标记为QUESTION 1
和QUESTION 2
的问题。
export function sendRequestAndLoadResponseForAllMemberContractInfo() {
return function sendRequestAndLoadResponseForAllMemberContractInfoThunk(dispatch) {
dispatch(getRequestsAction());
return returnPromiseWithAllMemberContracts()
.then(promiseWithAllMemberContracts => {
// Step 1) get all member ids in response
let contracts = promiseWithAllMemberContracts.response.contract;
let memberContractInfo = []; // <==== I want to store result of all 2nd promises here
for (let i in contracts) {
const memberID = contracts[i].member_id;
returnPromiseWithAllMemberInfo(memberID)
.then(secondAPICallResponse => {
// Step 2) make 2nd API call using memberIDs as parameter
memberContractInfo.push(secondAPICallResponse);
console.log('secondAPICallResponse = ', secondAPICallResponse);
if (memberContractInfo.length === 2) {
console.log('memberContractInfo.length = 2');
// QUESTION 1: I can access memberContractInfo here but I there must also be
// another place I can access it right?
}
})
}
console.log('memberContractInfo = ', memberContractInfo); // <== QUESTION 2: Why is this empty?
});
}
}
function returnPromiseWithAllMemberContracts() {
return fetchData('/api-proxy/contract/contract');
}
function returnPromiseWithAllMemberInfo(memberID) {
let servicePath = '/api-proxy/member?id='.concat(memberID);
console.log('fetchData(', servicePath);
return fetchData(servicePath);
}
答案 0 :(得分:0)
您可以在memberContractInfo
声明的范围内的任何位置访问then(promiseWithAllMemberContracts => {}
。
memberContractInfo
在console.log('memberContractInfo = ', memberContractInfo);
中为空,因为您在实际解决承诺之前就已达到此声明。
如@bergi所述,您需要使用Promise.all
而不是循环。
Promise.all(contracts.map((contract) => {
return returnPromiseWithAllMemberInfo(contract.member_id);
})).then(values => {
// values has response from all the above API calls stored in it
return values;
}).then((memberContractInfo) => {
console.log(memberContractInfo.length);
// this will give you correct value.
})