[英]How to chain requests synchronously with axios?
Suppose I have in my code several places with something like 假设我在代码中有几个地方,例如
axios({
method: 'post',
url: myurl,
data: mydata
}).then(...)
I would like the various axios requests to be executed synchronously : the next one must wait for the then
callback of the previous one before it is sent to the server. 我想不同的Axios公司请求同步地执行:下一个必须等待
then
前一个回调,然后发送到服务器。
It seems that what I ask is exactly what promises can offer you (by chaining several then
, say). 看来,我要问的就是诺言可以为您提供什么(通过链接多个
then
,比如说)。 Since Axios is Promise based, I suppose it should somehow be able to do that. 由于Axios基于Promise,因此我认为它应该能够做到这一点。 But oddly enough, I cannot find this information anywhere.
但奇怪的是,我在任何地方都找不到此信息。
Note that I do not know in advance all the requests to be sent : there is a first one, then a second one might arrive before the first one finishes, or not, and so on. 请注意,我并不预先知道要发送的所有请求:有一个请求,然后一个可能在第一个请求完成之前到达,否则,第二个请求可能不会到达,依此类推。
ADD ON : Also I think I see how to achieve what I ask by making the Promises myself, sending directly Asynchronous Http Requests. 添加:另外,我想我也可以通过自己制作Promises,直接发送异步Http请求来实现我的要求。 It just seems weird that the library designed for that would not offer this possibility.
似乎很奇怪,为此设计的库无法提供这种可能性。
Ok, I did not know the following : if the return of the function passed as parameter to a then
call returns a Promise, then this promise is resolved before further then
calls. 好吧,我不知道以下几点:如果作为参数传递给函数的返回
then
调用返回一个承诺,那么这个承诺是前进一步解决then
调用。 Concretely, I think the following achieve what I want : 具体来说,我认为以下实现了我想要的:
Once, at the beginning of the script: 一次,在脚本开头:
let requestSender = Promise.resolve('');
Then whenever I need to send a request : 然后,每当我需要发送请求时:
requestSender.then(prev =>
axios({method: 'post', url: myurl, data: mydata}).then(...))
that way, each new axios request will wait for the previous one to end before being sent. 这样,每个新的axios请求将在发送之前等待上一个请求结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.