簡體   English   中英

Nodejs 多個 axios 獲取請求返回一個 Primise

[英]Nodejs multiple axios get requests return a Primise

如何從多個axios獲取請求中返回Promise
我有以下代碼。


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;
}

我想要實現的是:

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);
    });
}

這就是為什么我可以並行執行所有請求的原因。

但是,當我更新 function getData(dataURI)以返回return new Promise ,我收到await axios錯誤。

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

    // Same code as above 
 
   });
}

我得到錯誤:

SyntaxError: await is only valid in async function

由於Promise不是異步的,我無法在 Promise 中等待。

你有沒有嘗試過:

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

// Same code as above 

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM