Created
November 14, 2016 13:02
-
-
Save yysun/d171942eec88df5f2a1feed8d0424336 to your computer and use it in GitHub Desktop.
TypeScript async/await example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); | |
const main = async () => { | |
console.log("Hello"); | |
for (let i = 0; i < 3; i++) { | |
await delay(500); | |
console.log("."); | |
} | |
console.log("World!"); | |
} | |
main(); | |
const url = '/'; | |
// callback implementation | |
const ajax = (url, options, success, err = null) => { | |
let request = new XMLHttpRequest(); | |
request.onload = success | |
request.onerror = err; | |
request.open(options.method, url, true); | |
request.send(); | |
} | |
// use callback | |
const getHomePage = () => ajax(url, {method:'get'}, | |
e => console.log(e), | |
e => console.error(e) | |
); | |
getHomePage(); | |
// Promise implementation | |
const fetch = (url, options = {method:'get'}) => new Promise((resolve, reject) => { | |
let request = new XMLHttpRequest(); | |
request.onload = resolve | |
request.onerror = reject; | |
request.open(options.method, url, true); | |
request.send(); | |
}); | |
// use Promise | |
const getHomePage1 = () => { | |
fetch(url) | |
.then(e => console.log(e)) | |
.catch(e => console.log(e)); | |
} | |
getHomePage1(); | |
// Use Promise with async/await | |
const getHomePageAsync = async ()=> { | |
try { | |
const e = await fetch(url); | |
console.log(e); | |
} | |
catch(ex) { | |
console.error(ex); | |
} | |
} | |
getHomePageAsync(); | |
// convert callback style to Promise: wrap callback with Promise | |
const fetchAsync = (url, options = {method:'get'}) => new Promise((resolve, reject) => ajax(url, options, resolve, reject)); | |
// convert promise calls to callbacks | |
const callbackFetch = (url, options, success, err = null) => fetch(url, options).then(success).catch(err); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment