我想运行一个调用后端的axios请求循环,并在重定向页面之前等待所有响应。
在下面的代码中,一旦收到200 OK的响应,我希望将其推送到promiseArray。如果我收到所有的promiseArray项目,我想重定向页面到另一个网址。
就我的情况而言,代码似乎并没有真正停下来等待响应。它为axios请求循环3次,但它没有等待响应,而是直接运行重定向部分。
有什么想法吗?
function test(){
var response = undefined;
var length = 3;
var promiseArray = [];
for(var a=0;a<length;a++){
var link = 'https://'+hostname+'/';
var apiUrl = 'api/xxx';
var token = "123";
axios.create({
baseURL: link,
timeout: 60000,
headers: {
Authorization: token
}
}).post(apiUrl, {
...
}).then(res => {
console.log(res);
promiseArray.push(res);
}).catch(err=>{
console.log("err");
console.log(err);
});
}
response = await axios.all(promiseArray);
if(response!=undefined){
window.location.replace("https://"+hostname+"/abc");
}
}
发布于 2019-06-14 08:56:31
这是因为promiseArray
是空的,所以你要把结果推给它。将实际承诺推送到数组中。
async function test(){
var response = undefined;
var length = 3;
var promiseArray = [];
for(var a=0;a<length;a++){
var link = 'https://'+hostname+'/';
var apiUrl = 'api/xxx';
var token = "123";
promiseArray.push(
axios.create({
baseURL: link,
timeout: 60000,
headers: {
Authorization: token
}
}).post(apiUrl, {
...
})
)
}
response = await axios.all(promiseArray);
if(response!=undefined){
window.location.replace("https://"+hostname+"/abc");
}
}
发布于 2019-06-14 09:04:35
您希望在重定向页面之前等待所有响应,所以您需要使用Promise.all()
以下来自MDN的示例
var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [3, 42, "foo"]
发布于 2019-06-14 09:31:44
如果您已经在一个地方使用async / await
,为什么不到处使用它:
async function test(){
var length = 3;
for(var a=0; a<length; a++){
var link = 'https://'+hostname+'/';
var apiUrl = 'api/xxx';
var token = "123";
let res = await axios.create({
baseURL: link,
timeout: 60000,
headers: {
Authorization: token
}
}).post(apiUrl, {
...
});
/* Do whatever you need with res */
}
window.location.replace("https://"+hostname+"/abc");
}
https://stackoverflow.com/questions/56594683
复制相似问题