下面的 arr 变量是类似数组的集合。
function site1(url){
return axios.get(url)
.then((response)=>{
if(response.status==200){
//code for getting data
//arr=[]---------initial value (globally declared variable)
for(i=1;i<=limit;i++){
arr.push(someData);
//after this push arr=[[item1,item2,item3,item4,item5]]
//arr is an collection of similar arrays
//there are many links one for each array inside arr
//-----operation here to get someLink-------
for(a=0;a<arr.length;a++){
someOtherSite(somelink,arr).then((data)=>{
arr=data;
});
}
}
}
return arr;
})
}
function someOtherSite(url,arr){
return axios.get(url)
.then(response=>{
//get some dataItem
arr[arr.length-1].push(dataItem);
return arr;
})
}
用于函数调用:
site1(url).then(data=>{
console.log(data);
})
我希望 arr 的值是这样的: arr=[[item1,item2,item3,item4,item5,dataItem],.......] 但返回发生在之前,并且显示的 arr 值没有 dataItem。 如何让值的返回等待并在过程完成后发生。
最佳答案
axios是一个基于promise的HTTP客户端,所以需要等待axios返回,对于axios.get使用async function和await,也可以使用Promise 等待操作https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
以下是有关您的代码的示例:
function site1(url){
return new Promise(async(resolve,reject)=>{
await axios.get(url)
.then((response)=>{
//code for getting data
//arr=[]---------initially globally declared
for(i=1;i<=limit;i++){
arr.push(someData);
for(a=0;a<arr.length;a++){
someOtherSite(somelink,arr).then((data)=>{
arr=data;
});
}
}
resolve(arr)
})
.catch(err=>{
reject(err)
})
})
}
function someOtherSite(url,arr){
return new Promise(async(resolve,reject)=>{
await axios.get(url)
.then(response=>{
//get some dataItem
arr[arr.length-1].push(dataItem);
resolve(arr);
})
.catch(err=>{
reject(err)
})
})
}
用于函数调用:
site1(url).then(data=>{
console.log(data);
})
关于javascript - axios中如何处理异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60888804/