[英]async await function returns promise instead of string
I am new to javascript , Here I have a following graphql
我是 javascript 新手,这里我有一个以下graphql
getId = async dataId => {
let finalData = await apolloClient.query({
query: GET_DOOR_ORDER,
variables: {
Id: dataId
}
})
return finalData?.value
}
Now, I am calling this function现在,我正在调用这个函数
let orderIdForbuyingSessionsEdit = '';
orderIdForbuyingSessionsEdit = this.getClientOrderIdFromDoorOrder(orderId)
This gives an error这给出了一个错误
Type 'Promise<any>' is not assignable to type 'string'.ts(2322)
How do I get string as a return value from a async function.如何从异步函数获取字符串作为返回值。
In order to call async functions you need to put await
keyword where you make a call.为了调用异步函数,您需要将await
关键字放在您进行调用的位置。 This will wait till promise is resolved and return the value.这将等到承诺得到解决并返回值。
In the text of your question, the first getId
function is a good example of the async function call.在您的问题文本中,第一个getId
函数是异步函数调用的一个很好的例子。 You need to do the same in place where you call it too:你也需要在你调用它的地方做同样的事情:
async
keyword prefix调用另一个异步函数的函数应该有async
关键字前缀await
keyword prefix将要调用的异步函数应该有一个await
关键字前缀So in order to call your getId
function properly somewhere you need to act like this:因此,为了在某处正确调用您的getId
函数,您需getId
:
async function myMethod() {
let value = await getId(123);
console.log(value);
}
Read more about async/await here .在此处阅读有关 async/await 的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.