JavaScript
x
35
35
1
function axiosGetJSON(pathToFile) {
2
let shortcuts = [];
3
axios.get(pathToFile).then((response) => {
4
for (i of response.data["shortcuts"]) {
5
shortcuts.push(i);
6
console.log("OUT: ",shortcuts.length)
7
console.log(i);
8
}
9
});
10
console.log("OUT_RESULT: ",shortcuts.length)
11
return shortcuts;
12
}
13
14
function createShortcutsTable(shortcuts, requiredData) {
15
let shortcutsTable = document.createElement("table");
16
let labelString = document.createElement("tr");
17
for (label of requiredData) {
18
let labelCell = document.createElement("th");
19
labelCell.innerHTML = label;
20
labelString.appendChild(labelCell);
21
}
22
shortcutsTable.appendChild(labelString);
23
for (shortcut of shortcuts) {
24
let tableString = document.createElement("tr");
25
for (label of requiredData) {
26
let stringCell = document.createElement("th");
27
stringCell.innerHTML += shortcut[label];
28
tableString.appendChild(stringCell);
29
}
30
shortcutsTable.append(tableString);
31
}
32
document.body.append(shortcutsTable);
33
}
34
createShortcutsTable(axiosGetJSON('json/shortcuts.json'),['name','url'])
35
json/shortcuts.json file is:
JavaScript
1
17
17
1
{
2
"shortcuts": [
3
{
4
"id":1,
5
"name": "123",
6
"url": "123",
7
"img": "123"
8
},
9
{
10
"id":2,
11
"name": "123",
12
"url": "123",
13
"img": "/img/prakticum-logo.png"
14
}
15
]
16
}
17
I’ve tried async and await as well as passing one of the functions as a callback. Nothing succeeded:( I think function works bad because of asynchrony. I just started learning of JS, so i am beginner and kindly ask for help! Thanks!
Advertisement
Answer
Because axios
already have a callback function, so you only need to call createShortcutsTable(shortcuts ,['name','url'])
after iterate and call function axiosGetJSON('json/shortcuts.json');
alone
JavaScript
1
14
14
1
function axiosGetJSON(pathToFile) {
2
let shortcuts = [];
3
axios.get(pathToFile).then((response) => {
4
for (i of response.data["shortcuts"]) {
5
shortcuts.push(i);
6
console.log("OUT: ", shortcuts.length)
7
console.log(i);
8
}
9
createShortcutsTable(shortcuts, ['name', 'url']);
10
});
11
}
12
13
axiosGetJSON('json/shortcuts.json');
14
If you want to use async/await (I don’t recommend it because don’t need to). You have to turn axiosGetJSON
function into an async function, which will return a promise to handle by .then(function)
JavaScript
1
16
16
1
async function axiosGetJSON(pathToFile) {
2
let shortcuts = [];
3
let response = await axios.get(pathToFile);
4
for (i of response.data["shortcuts"]) {
5
shortcuts.push(i);
6
console.log("OUT: ", shortcuts.length)
7
console.log(i);
8
}
9
console.log("OUT_RESULT: ", shortcuts.length)
10
return shortcuts;
11
}
12
13
axiosGetJSON('json/shortcuts.json').then(function (result) {
14
createShortcutsTable(result, ['name', 'url']);
15
});
16