我有以下代码:
var arrayAxios = [];
const array = async() => {
await sleep(3000);
_.forEach(tasks, task => {
let res = _.includes("selected", task.value);
if (res) {
this.axios
.get(url, { params: { data1 } })
.then(response => {
arrayAxios.push(this.axios.post(url, { dataAAA }));
});
}
});
};
var promises = async() => {
const arrayAxios = await array();
await Promise.all(arrayAxios)
.then(response => {
resetAll_dataAAA(); // <--- my dataAAA in arrayAxios are reset before post in Promise.all!
})
.catch(error => {
console.log(error);
});
};
promises();
在将数据发布到DDBB中之前,将执行函数“ resetAll_data()”。我找不到问题。
有什么建议吗?
非常感谢您!
答案 0 :(得分:1)
您正在寻找
async function array() {
await sleep(3000);
var arrayAxios = []; // declare the array locally
_.forEach(tasks, task => {
let res = _.includes("selected", task.value);
if (res) {
arrayAxios.push(this.axios
// ^^^^^^^^^^^^^^^ push to the array immediately, not asynchronously
.get(url, { params: { data1 } })
.then(response => {
return this.axios.post(url, { dataAAA }));
// ^^^^^^ chain the promises
})
);
}
});
return arrayAxios;
//^^^^^^ give the result to the caller
}
答案 1 :(得分:0)
我已经简化了您的示例,因此希望您可以了解正在发生的事情:)
您需要从一个数组中返回一个promise数组,以便能够使用Promise.all来解决它们。
使用await Promise.all().then
,使用await
或then
数组从不返回请求承诺,因此在等待时将立即解决
我不相信睡眠也是节点中的功能。
任何问题都让我知道很乐意为您提供帮助。
const axios = {
get: async(task) => {
return task.res;
},
post: async(task) => {
return task;
}
}
const tasks = [{url: 'getting', res: {got: 'got the thing', post: 'thing to post'}}, {url: 'getting 2', res: {got: 'got the thing 2', post: 'thing to post 2'}}]
const getRequest = async(url = '') => {
const res = await axios.get(url)
console.log(res.got)
return postRequest(res.post)
}
const postRequest = async (url = '') => {
const res = await axios.post(url)
console.log(res)
return res;
}
const array = async() => {
const createRequests = async task => {
return getRequest(task)
}
return tasks.map(createRequests).filter(Boolean);
};
const promises = async() => {
console.log('waiting')
const res = await array()
const all = await Promise.all(res)
console.log('awaited')
console.log('can call your reset')
};
promises();