繁体   English   中英

调用Promise时如何让function同步返回值?

[英]How to get function to return value synchronously when calling a Promise?

我有一个 function 调用一个异步方法,该方法返回一个 promise。 我需要 function 根据承诺的解析值返回值。 但是当我尝试这样做时,typescript 会抛出一个错误,指出该值在定义之前正在使用。

const myFunction = async (id: string): MyProductInterface {

  let isvalidProduct = false;
  let myProduct: MyProductInterface;

  await myClient.clientmethod(id)
  .then((response) =>{
    if (response == "valid"){
      isvalidProduct = true; 
    }
  })

  if(isvalidProduct){
    myProduct = //code to create MyProductInterface object with some values set to true;
  }else{
    myProduct = //code to create MyProductInterface object with some values set to false;
  }

  return myProduct;
}

clientmethod(id)方法是异步的,但我需要等待 promise 解决,因为我返回的myProduct取决于 promise 的分辨率。 我怎样才能让它工作?

不要让它变得比必要的更复杂:

async function myFunction(id: string): Promise<MyProductInterface> {

  const response = await myClient.clientmethod(id);
//^^^^^^^^^^^^^^^^

  if (response == "valid") {
    return … //code to create object with some values set to true;
  } else {
    return … //code to create object with some values set to false;
  }
}

但是,不, myFunction(…)仍然是异步的,并且总是会返回一个 promise,不可能让它同步返回。 await所做的只是确保检查response并在myClient.clientmethod(id)完成后创建结果 object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM