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

Node.js中如何让uploadPhoto函数正确返回已上传图片的id

问题原因
  • 你写的两版代码核心问题都是没有把回调风格的上传API适配为Promise,而async/await语法本身是基于Promise实现的,直接对回调风格函数加await、在回调里写return都没法把结果透传到外层函数。
  • 第一版里return data.id是回调函数的内部返回值,和外层uploadPhoto的返回值没有任何关系;且回调风格的client.uploadFile本身不返回Promise,前面的await无效。
  • 第二版里自定义的uploadF是普通回调函数,没有返回Promise实例,对它做await拿到的结果永远是undefined。
修改方案

只需要把client.uploadFile的回调逻辑包装进Promise,在回调中成功时resolve结果、失败时reject错误,就能正常适配async/await语法:

async function uploadPhoto(image, name) {
    try {
        // 可替换为非阻塞写法:const file = await fs.promises.readFile(image)
        const file = fs.readFileSync(image);
        
        const photoId = await new Promise((resolve, reject) => {
            client.uploadFile({
                name: image,
                type: "image/jpg",
                bits: file
            }, (error, data) => {
                if (error) return reject(error);
                // 注意核对接口返回的id字段,你两版代码分别写了data.id、data.attachment_id,按实际返回调整
                resolve(data.id ?? data.attachment_id);
            });
        });

        return photoId;
    } catch (err) {
        console.log('上传失败:', err);
        // 需要外层捕获错误就throw,不需要可按需返回默认值
        throw err;
    }
}
调用方式

保持你原有调用逻辑不变即可:

let photoId = await uploadPhoto(image, name);

这里拿到的photoId就是你需要的整数类型图片id。

补充说明
  • 如果你的client本身支持Promise风格调用(大部分新版SDK都支持),可以直接const data = await client.uploadFile({...})然后return data.id,不需要手动包装Promise,你可以先查下对应SDK的文档确认。
  • 同步方法fs.readFileSync会阻塞Node.js事件循环,生产环境建议替换为fs.promises.readFile的异步写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:45:33