I am used to await but eslint hates it in a loop. Eslint does not like defining a function in a loop as well. Therefore I ended up with the following snippet in Vuex script:
// wait until the file is synchronized
let waitTime = 100;
let fileExists = false;
const checkSync = (res, i) => {
console.log(res.status);
if (res.status === 200) {
fileExists = true;
console.log('Status 200, setting fileExists=true');
} else if (res.status === 404) {
Vue.$log.debug(`Image not ready for download ${res.status}`);
setTimeout(() => { waitTime = (i < 4) ? 200 : 1000; }, waitTime);
console.log(`waitTime = ${waitTime}`);
}
};
for (let i = 0; !fileExists && i < 5; i += 1) {
console.log(`fileExists = ${fileExists}`);
axios.head(`${response.data.data.url}`).then(resp => checkSync(resp, i));
}
But the log reveals that the first log statement inside the loop is executed one by one and the second statement with a promise/resolve is executed when the loop is finished. I could rewrite the code to await and ignore eslint, but I hope I finally get deeper knowledge of good old promises.
fileExists = false
fileExists = false
fileExists = false
fileExists = false
fileExists = false
items.js:175 200
items.js:178 Status 200, setting fileExists=true
items.js:175 200
items.js:178 Status 200, setting fileExists=true
items.js:175 200
items.js:178 Status 200, setting fileExists=true
items.js:175 200
items.js:178 Status 200, setting fileExists=true
items.js:175 200
items.js:178 Status 200, setting fileExists=true
UPDATE
The way I do it usually. Eslint complains but the code is triggered by a users when they upload new picture so I do not need to care about efficiency.
// wait until the file is synchronized on backend to www node
let waitTime = 100;
for (let i = 0; i < 5; i += 1) {
// eslint-disable-next-line no-await-in-loop
const head = await axios.head(response.data.data.url);
if (head.status === 200) {
return response.data;
} else if (head.status === 404) {
Vue.$log.debug(`Image not ready for download ${head.status}`);
// eslint-disable-next-line no-loop-func
setTimeout(() => { waitTime = (i < 4) ? 200 : 1000; }, waitTime);
console.log(`waitTime = ${waitTime}`);
}
}