Javascript async / await Frontend-IL

13
Fulfill the promise Async await with javascript Ran Wahle

Transcript of Javascript async / await Frontend-IL

Fulfill the promise Async await with javascript

Ran Wahle

What will we see today?

Promise patterns (and standards)

Async / await

Promise creation demo

ES2015 promise

One standard (No more “Success”)

Native javascript implementation

Native support in new APIs

Using Fetch API

async await

Writing asynchronously with “synchronous” syntax

await keyword “turns” a promise to its resolved value

Async await vs. Promise

const fetchPromise = fetch( '/allmessages').then( (response) => {

return response.json().then(messages => {messages.forEach(message => {

//present messages});

}, error => {console.error(error);

});

try {const response = await fetch('/allmessages');const messages = await response.json();messages.forEach(message => {

//present messages});

} catch (error) {console.error(error);

}

Where is the callback?

try {const response = await fetch('/allmessages');

const messages = await response.json();messages.forEach(message => {

//present messages});

} catch (error) {console.error(error);

}

Create promise

Callback

Why marking with async?

You’re not really synchronous when using await

Whenever there’s await keyword ,and after it, you are on the callback.

You should not assume that you are running synchronously

Async / Await

Platform support

Lets wrap

Async await is for code simplification

No synchronous code exists below await

We should mark await-using function with async

Async marked function returns promise.

Thanks

Ran Wahle

http://blogs.microsoft.co.il/ranw

Twitter: @ranwahle

[email protected]

Linkedin : https://il.linkedin.com/in/ranwahle