简体   繁体   中英

Nodejs multiple axios get requests return a Primise

How to return a Promise from the multiple axios get requests?
I have below code.


async function main() {
    const URL_1 = 'abc.com/get1/data1';
    const result_1 = await getData(URL_1);

    const URL_2 = 'abc.com/get2/data2';
    const result_2 = await getData(URL_2);
}

async function getData(dataURI) {
    let getURI = dataURI;
    
    const config = {
      headers: {
        Authorization: `Bearer ${my-token-text}`,
      },
    };
    
    var finalData = [];

    // until we get the next URL keep sending the requests 
    while (getURI != null) {
        try {
            const getResult = await axios.get(getURI, config);
            if (getResult.status === 200) {
                const receivedData = getResult.data.value;
                finalData.push(...receivedData);
                
                // check if we have nextLink in the payload
                if (Object.prototype.hasOwnProperty.call(getResult.data, 'nextLink')) {
                    getURI = getResult.data.nextLink;
                } else {
                    getURI = null;
                    return finalData;
                }
            }
        } catch (err) {
            break;
        }
    }
    return null;
}

What I am trying to achieve is:

async function main() {
    const URL_1 = 'abc.com/get1/data1';
    const result_1 = getData(URL_1);
    promisesArray.push(result_1);

    const URL_2 = 'abc.com/get2/data2';
    const result_2 = getData(URL_2);
    promisesArray.push(result_2);

    await Promise.allSettled(promisesArray).then((results) => {
        console.log('Promise All Done: ', results);
    });
}

This why I can perform all the requests in parallel.

But when I update the function getData(dataURI) to return return new Promise then I get error for await axios .

async function getData(dataURI) {
   return new Promise((resolve, reject) => {

    // Same code as above 
 
   });
}

I get error:

SyntaxError: await is only valid in async function

As Promise is not async I cannot await in the Promise.

Have you tried:

return new Promise(async (resolve, reject) => {

// Same code as above 

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM