You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

函数返回多值报错:TypeError: createInvoice不可迭代或非函数

TypeError: createInvoice不是函数或返回值不可迭代的问题排查

尝试通过解构赋值获取createInvoice函数返回值时触发以下错误:

node:events:505
      throw er; // Unhandled 'error' event
      ^

TypeError: createInvoice is not a function or its return value is not iterable
    at Client.<anonymous> (C:\Users\Utente\Desktop\sito\InvoiceBot\index.js:101:63)
    at Client.emit (node:events:527:28)
    at InteractionCreateAction.handle (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
    at Object.module.exports [as INTERACTION_CREATE] (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:354:31)
    at WebSocketManager.<anonymous> (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:238:12)
    at WebSocketManager.emit (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\@vladfrangu\async_event_emitter\dist\index.js:282:31)
    at WebSocketShard.<anonymous> (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\@discordjs\ws\dist\index.js:1103:51)
    at WebSocketShard.emit (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\@vladfrangu\async_event_emitter\dist\index.js:282:31)
    at WebSocketShard.onMessage (C:\Users\Utente\Desktop\sito\InvoiceBot\node_modules\@discordjs\ws\dist\index.js:938:14)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:384:10)
    at processTicksAndRejections (node:internal/process/task_queues:85:21)

相关代码

createInvoice函数实现

function createInvoice(item_name, note_message, quantity, cost, payer_email){ 

    let create_invoice_json = {
        "merchant_info": {
            "email": config.emailAddress,
            "business_name": config.business_name,
        },
        "billing_info": [
        {
        "email": payer_email,
        }
        ],
        "items": [
            {
                "name": item_name,
                "quantity": quantity,
                "unit_price": {
                    "currency": "USD",
                    "value": cost,
                }
            },
        ],
        
        "note": note_message,
        }

    paypal.invoice.create(create_invoice_json, function (error, invoice) {
        if (error) {
            throw error;
        } else {
            //console.log(invoice)
            return [invoice.id, invoice.status, invoice.billing_info[0],  invoice.items[0], invoice.items[1], invoice.invoice_date, invoice.total_amount[1]] 
        }
    });
}

解构赋值调用代码

const [id, status, payer, item, q, date, price] = createInvoice(item_name, note_message, quantity, cost, payer_email)

问题原因

  1. 函数无返回值:createInvoice函数本身没有任何return语句,默认返回undefined,而undefined不可迭代,解构赋值时直接触发TypeError。
  2. 回调return无效:回调函数里的return仅属于回调自身,不会作为外层createInvoice函数的返回值传递出去。
  3. 异步逻辑未处理:paypal.invoice.create是异步操作,直接同步解构根本无法获取异步生成的发票数据。

解决方案

方案1:封装为Promise并使用async/await

修改createInvoice使其返回Promise,调用时用await等待异步结果:

function createInvoice(item_name, note_message, quantity, cost, payer_email){ 
    return new Promise((resolve, reject) => {
        let create_invoice_json = {
            "merchant_info": {
                "email": config.emailAddress,
                "business_name": config.business_name,
            },
            "billing_info": [
                {
                    "email": payer_email,
                }
            ],
            "items": [
                {
                    "name": item_name,
                    "quantity": quantity,
                    "unit_price": {
                        "currency": "USD",
                        "value": cost,
                    }
                },
            ],
            "note": note_message,
        };

        paypal.invoice.create(create_invoice_json, function (error, invoice) {
            if (error) {
                reject(error); // 将错误传递给调用方
            } else {
                // 注意:invoice.items只有1个元素,invoice.items[1]会是undefined,需根据实际情况调整
                resolve([invoice.id, invoice.status, invoice.billing_info[0], invoice.items[0], invoice.items[1], invoice.invoice_date, invoice.total_amount[1]]);
            }
        });
    });
}

调用时需在async函数内使用await:

// 确保调用代码所在的函数是async函数
async function processInvoice() {
    try {
        const [id, status, payer, item, q, date, price] = await createInvoice(item_name, note_message, quantity, cost, payer_email);
        // 处理获取到的发票数据
    } catch (err) {
        console.error('生成发票失败:', err);
        // 错误处理逻辑
    }
}

方案2:使用util.promisify转换异步方法

如果Node.js环境支持,可通过util.promisify将回调式的方法转为Promise版本:

const { promisify } = require('util');
// 将paypal的create方法转为Promise版本
const createInvoiceAsync = promisify(paypal.invoice.create);

async function createInvoice(item_name, note_message, quantity, cost, payer_email){ 
    let create_invoice_json = {
        // 同之前的JSON结构
    };
    try {
        const invoice = await createInvoiceAsync(create_invoice_json);
        return [invoice.id, invoice.status, invoice.billing_info[0], invoice.items[0], invoice.items[1], invoice.invoice_date, invoice.total_amount[1]];
    } catch (error) {
        throw error;
    }
}

调用方式和方案1一致,需在async函数内使用await。

额外注意事项

  • 检查invoice.items[1]:你的items数组仅包含一个元素,此处会获取到undefined,建议根据实际业务逻辑调整返回值结构。
  • 错误处理:必须通过try/catch捕获异步操作的错误,避免出现未处理的Promise rejection或error事件。

内容的提问来源于stack exchange,提问作者KaoDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 10:04:56