簡體   English   中英

在 Node.js 中為 function 定義等待

[英]defining a await for the function in Node.js

我正在嘗試從 3 個相互依賴的 API 獲取響應數據。 當我調用每個外部 API 時,響應具有一組外部 API,因為我需要所有 3 個外部 API 響應。 這是代碼:

const options = {
    JSON: true,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        "Authorization": process.env.authID,
    },
    body: {},
    uri: ''
};

app.post('/sync', async (req, res) => {
    try {
        let getFirstAPI = Object.assign({}, options);
            getFirstAPI.uri = 'https://abcde';   // first API 
        request(getFirstAPI, function (err, httpResponse, body) {
            Promise.all(body.projects.map((prct) => getVuln(prct))).then(rs => {
                res.JSON({ message: rs });
            });
        });
    }
});
async function getVuln(prodId) {
    try {
        let getSecondAPI= Object.assign({}, options);
        getSecondAPI.uri = 'abcd' + prodId.id + '/abc';  //Second API
        return await new Promise((resolve, reject) => {
          request(getSecondAPI, function (err, httpResponse, body) {
                let final = {
                    products: [],
                    dataList: []
                }
                final.products.push({
                    product_id: prodId.id,
                    product_name: prodId.abc,
                    product_ver: prodId.wdc
                })

                body.issues.forEach(csa => {
                  final.dataList.push({
                        product_id: prodId.id,
                        version: csa.Versions,
                        name: csa.Name,
                        pathJsonValue:await getPathfun(csa.link) //Here i am getting error "SyntaxError: Unexpected identifier"
                    });
                });
                resolve(final);
            });
        })

    }
}
 function getPathfun(urlStr) {
    let getPathUrl = Object.assign({}, options);
    getPathUrl.url = urlStr; 
    return new Promise((resolve, reject) => {
        request(getPathUrl, function (err, httpResponse, body) {
            resolve(body);
        });
    });
}

在“pathJsonValue”處,運行代碼時出現錯誤,如果我刪除等待,則“pathJsonValue”為空。 我附上了下面的錯誤圖片。 請幫我解決這個問題。 在此處輸入圖像描述

  1.  request(getSecondAPI, function (err, httpResponse, body) {

回調必須是 ASYNC function 才能在其中使用“等待”關鍵字。

  1. 'await' 關鍵字在“forEach”方法中不起作用。 改用 for...of 循環。

暫無
暫無

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

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