从promise中访问数据,调用另一个promise

时间:2016-04-20 00:40:46

标签: javascript promise redux es6-promise

我有一个承诺调用另一个承诺,但我不知道如何访问我试图存储所有承诺的变量memberContractInfo。在下面的代码中,我有两个标记为QUESTION 1QUESTION 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);
}

1 个答案:

答案 0 :(得分:0)

  1. 您可以在memberContractInfo声明的范围内的任何位置访问then(promiseWithAllMemberContracts => {}

  2. memberContractInfoconsole.log('memberContractInfo = ', memberContractInfo);中为空,因为您在实际解决承诺之前就已达到此声明。

  3. 如@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.
    })