简体   繁体   English

异步等待 function 返回未定义

[英]async await function returns undefined

I am trying to handle the "Error scenario" using async awaits but I get undefined as return value at Line 10.我正在尝试使用异步等待处理“错误场景”,但在第 10 行我得到 undefined 作为返回值。

let retries = 0;

async function getQueueItems() {
    return [1, 2, 3]
}

async function updateQueue(queueItem, message) {
    return 'updatedQueue';
}

async function saveToProcessedQueue(queueItem) {
    return "saved";
}

async function sendMail(queueItem) {
    try {

        // if(!error) // do something and return

        // handling the error scenario
        if ('error') {
            if (retries < 5) {
                console.log('retries ', retries);
                retries += 1;
                await sendMail(queueItem);
            } else {
                await updateQueue(queueItem, '');
                retries = 0;
                return { status: false };
            }
        } else {
            return { status: true, respObj: result };
        }
    } catch (error) {
        console.log('sendMail ', error);
    }
}

async function processBatch() {
    try {
        const queueItems = await getQueueItems();
        if (queueItems.length) {
            for (let index = 0; index < queueItems.length; index += 1) {
                const res = await sendMail(queueItems[index]); // LINE 10 undefined here
                if (res.status) {
                    await saveToProcessedQueue(queueItems[index]);
                }
            }
        } else {
            console.log('No queue items found to process');
            return;
        }
    } catch (error) {
        console.log('error message in process batch', error);
    }
}

processBatch();

I get undefined at const res = await sendMail(queueItems[index]);我在const res = await sendMail(queueItems[index]);处得到undefined even though I am returning false as return { status: false };即使我返回 false 作为return { status: false };

I'm guessing retries < 5 at some point, and since you don't return anything in that block, the final result will be undefined :我猜在某些时候retries < 5 ,并且由于您没有在该块中返回任何内容,因此最终结果将是undefined的:

try {

    // if(!error) // do something and return

    // handling the error scenario
    if ('error') {
        if (retries < 5) {
            console.log('retries ', retries);
            retries += 1;
            await sendMail(queueItem);
        } else {
            // ...
        }
    } else {
        // ...
    }

You probably just need to change it to:您可能只需要将其更改为:

retries += 1;
return sendMail(queueItem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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