If you want to apply the async
in the code of mounted
you can do it as follows:
...
async mounted() {
try {
let response = await axios.get('http://localhost:8080/wp-json/api/v1/skills');
this.skills = response;
} catch(e) {
console.error(e);
}
}
...
Asynchronous functions
The statement async Function defines an asynchronous function, which returns an object Asyncfunction.
You can also define asynchronous functions using a async expression Function.
When an asynchronous function is called, it returns a Promise. When the asynchronous function returns a value, a Promise
will be solved with the value returned. When the asynchronous function throws an exception or some value, the Promise
will be rejected with the value launched.
An asynchronous function may contain an expression await, which pauses the execution of the asynchronous function and waits for the resolution of the Promise
passed, and then resumes the execution of the asynchronous function and returns the solved value.
Simple Example
function resolverDepoisDe2Segundos(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function adicionar1(x) {
var a = resolverDepoisDe2Segundos(20);
var b = resolverDepoisDe2Segundos(30);
return x + await a + await b;
}
adicionar1(10).then(v => {
console.log(v); // exibe 60 depois de 2 segundos.
});
async function adicionar2(x) {
var a = await resolverDepoisDe2Segundos(20);
var b = await resolverDepoisDe2Segundos(30);
return x + a + b;
}
adicionar2(10).then(v => {
console.log(v); // exibe 60 depois de 4 segundos.
});
Hello wDrik, what is the need to use
try/catch
? Promise already does that for you. What part of the code do you want to protect against an error?– Sergio
Bro is that I am using Owl.Carousel to display the data that are returning.. only that the sometimes Carousel carega before the items in full and this Buga the layout.. already put a timeout.. msm so ñ solved.. I thought an async await might help! vlw!
– wDrik
You probably fill Carousel with the array data
skills
right? Try to put av-if="skills.length"
probably already solve this problem, no need for Try catch or timeout. If you want to post the whole code that I try later.– guastallaigor
Blz, man already understood the logic.. so using a Try, catch with async/await should be for a more specific case ? Vlw!
– wDrik