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

Expo上传音频到Cloudinary调用异步方法返回Promise状态对象如何解决

问题原因
  • uploadAudioToCloudinary是async异步函数,所有异步函数默认返回值都是Promise对象,你没有等待异步执行完成就直接打印变量,拿到的是处于pending状态的Promise实例,你看到的{"_U": 0, "_V": 0, "_W": null, "_X": null}就是React Native环境下未完成执行的Promise的内部状态标识。
  • 你的现有函数返回的是resData.url,如果需要获取secure_url还需要调整返回字段。
解决方案

首先修改上传函数的返回值,把需要的secure_url返回,同时补充错误捕获逻辑:

//send audio to cloudinary
async uploadAudioToCloudinary() {
  try {
    let base64Url = `data:audio/m4a;base64,${this.state.recordingBase64}`; //add base64
    let apiUrl = "https://api.cloudinary.com/v1_1/dxnblz2x7/upload";

    let data = {
      file: base64Url,
      upload_preset: "*******",
      resource_type: "video",
    };

    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const resData = await response.json();
    // 修改为返回secure_url
    return resData.secure_url;
  } catch (err) {
    console.error("音频上传失败", err);
    throw err;
  }
}

之后有两种方式获取返回的URL:

方式1:使用await获取(推荐)

保证调用该方法的外层函数也是async异步函数,在调用前加await关键字:

// 外层函数必须标注async
async yourCallingFunction() {
  const record = await this.uploadAudioToCloudinary();
  console.log("RECORD", record); // 这里就能拿到正常的url地址
  // 后续使用record的逻辑都写在这里
}

方式2:使用.then回调获取

如果不方便修改外层函数为异步,可以用Promise的then回调接收结果:

this.uploadAudioToCloudinary().then(record => {
  console.log("RECORD", record); // 这里获取url,后续逻辑写在回调内
}).catch(err => {
  // 自定义上传失败的处理逻辑
})

内容的提问来源于stack exchange,提问作者Wahas Ali Mughal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:03