I'm trying to add a property to the all allIco's object from the tgram array / axios api call. When I add the property using .map its value is undefined. I know it's because my api call is asynchronous but I can't figure out how to add an axios.all...any help would be appreciated :)
var allIcos = Object.assign(ico.results);
let tgram = [];
var result = [];
for (let i = 0; i < allIcos.length; i++) {
axios.get(`url=@${tgramUrl[allIcos[i].name]}`).then(response => {
tgram.push(response.data.result);
}).catch(err => console.log(err));
}
var result = allIcos.map((obj,i) => Object.assign({telegram:"test"}, obj));
this.setState({data: allIcos});
console.log(allIcos);
what about try promise.all
?
const promises = [];
for (let i = 0; i < allIcos.length; i++) {
promises.push(axios.get(`url=@${tgramUrl[allIcos[i].name]}`));
}
Promise.all(promises).then(function(values) {
console.log(values);
});
reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
我看到的唯一方法是每次axios调用都有响应时执行map和setState(在'then'子句内。除非可以对所有axios调用一次(然后,setState和map也应该在内部)然后,但您知道的)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.