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

如何从async异步函数中获取返回的字符串值而非Promise对象

问题原因

所有async关键字声明的函数,返回值都会被自动包装为Promise对象,你没有等待异步请求完成就直接读取返回值,拿到的自然是未完成的Promise实例,调用toString()也只会得到"[object Promise]"这类字符串,无法拿到接口返回的真实名称。

解决方法

步骤1:改造getUsernameProps为异步函数,等待请求结果

const getUsernameProps = async (id: string) => {
    // 等待getFriendName异步请求完成,拿到返回的字符串值
    const friendName = await getFriendName(id);
    const userNameProps: IUserName = {
        friendName: friendName,
        friendId: id
    }
    console.log("AAAAAAAAAAAAA", userNameProps) // 此时打印结果为{friendName: "sam", friendId: 1}
    return userNameProps
}

步骤2:调整getUsernameProps的调用方式

因为改造后的getUsernameProps本身也是async函数,返回值依然是Promise,所以调用时也需要等待异步完成:

方式1:在其他async函数内用await调用(推荐)

async function yourBusinessFunction() {
    const userProps = await getUsernameProps("你的用户id");
    // 后续依赖userProps的逻辑都放在await之后执行
    console.log(userProps.friendName) // 输出sam
}

方式2:用.then回调处理结果

如果调用位置不能声明为async函数,可以用Promise的.then方法获取结果:

getUsernameProps("你的用户id").then(userProps => {
    // 后续依赖userProps的逻辑都放在这个回调内执行
    console.log(userProps.friendName) // 输出sam
})

注意事项

所有依赖异步请求结果的逻辑,必须放在await之后或者.then回调内,不能在同步代码中直接读取async函数的返回值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:57:04