如何从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
相关产品推荐
相关产品推荐

