typescript 承诺永远不能兑现-只能得到另一个承诺

mcdcgff0  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(96)

我正在尝试调用外部服务。该调用似乎成功完成,但返回的只是一个Promise,如果我访问属性,它将返回另一个Promise。希望有其他人看到我做错了什么(我是第一次编写React的Java开发人员)。

function retrieveUserProfile() {
    const result = API.fetchProfile({
    include: 'field1, field2',
  });
  return result;
}

let userProfile = retrieveUserProfile()
  .then((result) => {
    return result.data;
  })

userProfile又是一个承诺。有什么想法吗?如果你需要更多的上下文,请告诉我。

bxgwgixi

bxgwgixi1#

JavaScript中的承诺是包含已解决、已拒绝或待定值的框。
它们只能通过.then()(对于解析值)或.catch()(对于拒绝值)方法访问。
从它们中的任何一个返回值都将创建一个包含新值的新承诺框。

const promise5 = Promise.resolve(5) // promise5 is a Promise box with `5` in it
const promise10 = promise5.then(n => n*2); // promise5 is a Promise box with `10` in it

不使用then()访问该值是不可能的,因为解析的值可能只存在于将来。
JavaScript承诺使用语法糖来处理promise:异步/等待

const resolved5 = await Promise.resolve(5) // resolved10 is `5`
const resolved10 = resolved5*2; // resolved10 is `10`

但是这将 Package 函数变成了Promise,因为需要用async标记任何使用await的函数:

async myAsyncFunction() { // returns a Promise
   const resolved5 = await Promise.resolve(5)
   const resolved10 = resolved5*2;
   // resolved10 is a number here, not a Promise
   // but will be wrapped in a Promise when returned.
   return resolved10;
}

相关问题