You need to enable JavaScript to run this app. 异步方法未等待Promise解决且调用async函数加await报错求助
优惠活动
大模型
产品
解决方案
定价
更多

异步方法未等待Promise解决且调用async函数加await报错求助

问题根源

1. setDimensions 内部写法错误,无法等待接口请求完成

你写的await Promise.resolve(function() { ... })完全无效:

  • Promise.resolve传入普通函数时,会直接把函数本身作为成功值返回,既不会执行这个函数,也不会等待函数内部的ns.get请求完成
  • 就算你手动执行了这个函数,也没有把内部的Promise返回给外层,await根本感知不到接口的执行状态

2. formatJson 调用_setDimensions未加await(以及加await报错的原因)

你遇到的SyntaxError: await is only valid in async function报错和被调用函数是不是async无关,唯一原因是:你写await的那行代码的直接外层作用域不是async函数。需要检查是否把await写在了formatJson内部嵌套的普通同步回调里,或是实际运行的formatJson没有加async关键字。


修复方案

第一步:修正setDimensions的异步逻辑

直接await ns.get返回的Promise即可,不需要套多余的Promise.resolve和匿名函数:

async function setDimensions(itemToUpdate, object) {
    try {
        if(itemToUpdate != null) {
            console.log("Loading dimensions");
            // 直接等待接口请求完成
            const res = await ns.get(`inventoryItem/${object['Item ID']}?expandSubResources=true`);
            console.log("Inventory Item Loaded. Updating dimensions...");

            itemToUpdate.consignments.push({
                consignmentID: object.conID,
                barcode: object.barcode,
                itemID: '', // leaving as empty for now
                width : res.data.custitem_width,
                length : res.data.custitem_length,
                height : res.data.custitem_height,
                weight : res.data.custitem_weight,
                fragile: object.fragile === 'T' ? 1 : 0,
                description: object.description
            });

            console.log("Dimensions Finalised");
        }
    } catch(err) {
        console.log(err);
        const message = `Error attempting to set the dimensions for ${object['Item ID']}`;
        console.log(message);
        throw new Error(message);
    }
}

第二步:在formatJson中正确添加await

只要你的formatJson确实声明为async函数,在_setDimensions调用前加await不会报错,参考写法:

async function formatJson(input, _sendToThirdParty, _handleLogs, _setDimensions) {
     // ...do some work here to format the payload
     if(onlineConnectionRequired) {
         // 加await等待异步逻辑执行完成
         await _setDimensions(itemToUpdate, object);
    } else {
         // Do non-online based transformations here
    }
    // 此处后续逻辑会等上面的异步操作全部完成后再执行
    // ...do more work after the above
}

如果加await仍报错,继续排查两点:

  • 写await的行是否在formatJson的直接作用域下,有没有嵌套在普通同步函数中(比如普通forEach回调里写await就会报错,需要改成for循环或者async回调)
  • 传入的_setDimensions参数确实是async的setDimensions函数,不是其他同步回调函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 00:45:03