Ukážka Async Await v JavaScript-e

Minimalistická ukážka použitia await/await v JavaScripte. Riadky 24,25 kde je použitý await sú zvýraznené. Viď vysvetlenie pod ukážkov kódu:

[code lang=“js“ highlight=“24,25″]
var data = {}

const task1 = () => {
return new Promise( (resolve, reject) => {
setTimeout( ()=>{
console.log(‚task 1 finished‘)
data.taks1 = 1
resolve()
}, 2000)
})
}

const task2 = () => {
return new Promise( (resolve, reject) => {
setTimeout( ()=>{
console.log(‚task 2 finished‘)
data.taks2 = 2
resolve()
}, 2000)
})
}

const mytasks = async () => {
await task1()
await task2()
}

mytasks()
.then( () => {
console.log(data)
})
.catch( (error) => {
console.log(error)
})
[/code]

Vysvetlenie:

– funkcia v ktorej je pužité await musí byť označená ako async
– await/async je vlastne „syntactic sugar“ pre Promis-es, preto voláme funkciu „mytasks“, v ktorej bol použitý „await“ ako Promis.

 

Foto: autor

Be the first to comment

Leave a Reply