如何致电承诺,然后在React JS中同步功能
我正在与React JS(前端)和C#(后端)合作。我正面临一个问题,即从React屏幕(TSX文件)调用客户端API调用。 此API调用正在返回承诺对象。但是问题在于我们正在使用的API调用中。然后函数以获取API调用的响应,并且此功能是异步工作的。它没有执行所有语句,然后立即返回到初始调用功能(.tsx文件)。
但是我想要一些我的API调用应该如何完全执行(然后在。下),然后它应该返回到调用功能。
请参阅下面的代码 -
StudentDetails.tsx-
------------------
StudentResults(id: number) {
//api call
this.StudentHandler.StudentDetail(id) //here id is the student id
//other operations/statements (these statements should only be called after complete api execution)
statement 1...
statement 2...
etc
}
StudentHandler.ts-
------------------
StudentDetail(id: number){
return this.studentApi.getStudentDetail(id)
.then(response => {
statement 1... (this statement is calling after api execution)
statement 2... (and this statement is not calling after first statement. It's going to 'setStudentResults' function of tsx file and after executing remaining statemetns it's coming here again at 'statement 2')
})
.catch(error => {
console.log(error)
})
}
I am working with React Js (frontend) and C# (Backend). I am facing a problem where I am calling a client api call from react screen (tsx file).
This api call is returning a promise object. But problem is in the api call we are using .then function for getting response of api call and this .then function is working asynchronously. It's not executing all the statements under .then function and immediately returning to the initial call function (.tsx file).
But I want some how my api call should execute completely (under .then function) and then it should return to the calling function.
Please see the code below-
StudentDetails.tsx-
------------------
StudentResults(id: number) {
//api call
this.StudentHandler.StudentDetail(id) //here id is the student id
//other operations/statements (these statements should only be called after complete api execution)
statement 1...
statement 2...
etc
}
StudentHandler.ts-
------------------
StudentDetail(id: number){
return this.studentApi.getStudentDetail(id)
.then(response => {
statement 1... (this statement is calling after api execution)
statement 2... (and this statement is not calling after first statement. It's going to 'setStudentResults' function of tsx file and after executing remaining statemetns it's coming here again at 'statement 2')
})
.catch(error => {
console.log(error)
})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将重写您的代码以阐明使用异步/等待的点:
I will rewrite your code to clarify the point of using async/await: