[英]How to use async functions within functions?
所以假設你有這個同步 function 你調用a和另一個異步 function b你想放在a中。 所以你會得到這樣的東西:
async function b(){
//some code here
}
function a(){
}
現在假設我們將一些代碼添加到a並調用b :
async function b(){
//some code here
}
function a(){
b()
//other code here
}
現在假設您只想在b返回其 promise 時在a中運行代碼。好吧,如果您可以直接訪問b那么一切都很好,只需將其同步 function。那會起作用,但如果您沒有訪問b 。 問題來了。 如果你特別想在b之后運行它,那么你可以使用類似.then() 的東西:
async function b(){
//some code here
}
function a(){
b().then(<results for example>=>{
//other code
})
}
但是,如果a是一個異步 function 怎么辦? 我可以使用 await 或類似的東西嗎?
你必須讓一個 function 異步並等待 b function,然后 b function 將返回數據,否則將返回 promise。
async function b(){
//some code here
}
async function a(){
const data = await b();
// Do something with data
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.