簡體   English   中英

Promise.all 不等待所有響應 Azure Node.js 功能

[英]Promise.all not waiting for all response Azure Node.js Function

嗨,我編寫了一個代碼,它將調用 n 次外部 api,然后它的響應將傳遞給另一個函數,最后合並的響應將由 Azure 函數返回,但似乎我沒有得到所有項目的響應。 每次運行此代碼時它都會不斷變化,我認為我的 promise.all 方法存在問題。 請查看我的代碼

const axios = require('axios');
let globalContext;
var  globalRes = { status: true, products: [] }
const extractProuctFromLUISRes = async (jsonRes, Query) => {
    var quantArray = [];
    var resp = { quantity: 1, UOM: "", query: Query }
    if (jsonRes.entities.hasOwnProperty("UOM") === true) {
        if (jsonRes.entities.UOM.length > 0) {
            resp.UOM = jsonRes.entities.UOM[0][0]
        }
    }
    globalRes.products.push(resp);
}

const splitAndGetProduct = async (text) => {
    //split based on \n
    splitedEmail = text.split("\n");
    let luisCallPromises = [];
    for (var i = 0; i < splitedEmail.length; i++) {
        if (splitedEmail[i].length > 5) {
            luisCallPromises.push(callLuisProducts(splitedEmail[i]));
        }
    }

    let luisResponses = await Promise.all(luisCallPromises);
    for (let luisResponseIterator=0; luisResponseIterator<luisResponses.length; ++luisResponseIterator) {
        if(luisResponses[luisResponseIterator])
            await extractProuctFromLUISRes(luisResponses[luisResponseIterator].prediction, luisResponses[luisResponseIterator].query);
    }
}

const callLuisProducts = async (utterance) => {
    return new Promise(async (resolve, reject) => {
        var finalApiCall = "#httpsCallquery=" + encodeURIComponent(utterance.substring(0, 500));
        //axios call
        try {
            let a = await axios.get(finalApiCall);
            if (a.status == 200) {
                var jsonBody = a.data;
                if (jsonBody.prediction.topIntent == "product") {
                    resolve(jsonBody);
                } else {
                    resolve(false);
                }
            } else {
                resolve(false);
            }
        } catch (error) {
            resolve(false);
        }
    });
}

module.exports = async function (context, req) {
    globalContext = context;
    var inputArray = JSON.parse(req.body.attachmentProcessed);
    await splitAndGetProduct(inputArray);
    finalResolve();
}

function finalResolve() {
    globalContext.res = {
        body: globalRes
    };
    globalRes = { status: true, products: [] }
    globalContext.done();
}

azure 函數不適用於箭頭函數。 你需要使用重寫你的代碼

try{ 
    let answer=await 
    }
catch(e){}

結構體

暫無
暫無

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

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