提问人:Natsuo 提问时间:9/28/2023 最后编辑:Peter BNatsuo 更新时间:9/28/2023 访问量:67
在异步函数中链接请求
Chaining requests inside async function
问:
我对在异步函数中链接请求感兴趣。
比方说,我需要在内部异步函数之后调用。
我会这样做:request2
request1
const someFunct = async () => {
await request1();
await request2();
...
}
但是如果我打电话给里面,它会起作用吗?是一回事吗?request2
request1().then()
const someFunct = async () => {
await request1()
.then(() => request2());
...
}
答:
如果要确保在异步函数中的 request1 之后调用 request2,则有几个选项。正如您在代码中提到的,使用 await 是一种常见且简单的方法,但您也可以通过使用 .then() 链接 promise 来实现这一点 以下是这两种方法的示例:
使用 await:
const someFunct = async () => {
await request1();
await request2();
// Any code that depends on the results of request1 and request2
}
使用 await 时,第二个请求 (request2()) 只会在第一个请求 (request1()) 完成后执行。这意味着 request2() 在 request1() 完成执行之前不会启动,并且它们将按顺序运行。 使用 .then():
const someFunc = () => {
return request1().then(() => {
return request2();
});
// ...
}
当你使用 .then() 时,你正在创建一个承诺链。在这种情况下,request2() 仅在 request1() 解析(成功完成)后调用。但是,这里的区别在于您没有使用 async/await,因此函数 someFunc 不是异步函数。您将在调用站点使用 .then() 或 async/await 处理 someFunc() 的结果。
总而言之,这两种方法都实现了链接请求的目标,但它们具有不同的语法和行为。如果要使用 async/await 并确保 request2() 在 request1() 完成之前不会启动,请使用第一种方法。如果您更喜欢使用 .then() 链接,如第二个示例所示,您也可以这样做,但请确保使用 .then() 处理结果,或者在必要时在调用站点等待。
评论
.then
async