[英]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.