Last active
October 17, 2019 15:11
-
-
Save uguraktas/2aed2ae821c32daf54f708a5b65a08c3 to your computer and use it in GitHub Desktop.
Javascript Callback, promise and await
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
//Dummy data | |
const data = [ | |
{ title: "Title 1", description: "Title Content 1" }, | |
{ title: "Title 2", description: "Title Content 2" } | |
] | |
//Example Callback | |
function getData() { | |
setTimeout(() => { | |
data.map((item, index) => { | |
console.log('getData', item, index) | |
}) | |
}, 1000); | |
} | |
function createData(newData, callback) { | |
setTimeout(() => { | |
data.push(newData); | |
callback() | |
}, 2000); | |
} | |
createData({ title: "Title 3", description: "Title Content 3" }, getData); | |
//Example Promise | |
function createData(post) { | |
return new Promise((resolve, reject) => { | |
data.push(post) | |
const error = false; | |
if (!error) { | |
resolve() | |
} else { | |
reject("Bir hata var!") | |
} | |
}) | |
} | |
createData({ title: "Title 3", description: "Title Content 3" }) | |
.then(getData) | |
.catch(err => console.log("createData Error ->", err)) | |
//Example async | |
async function init(){ | |
await createData({ title: "Title 3", description: "Title Content 3" }), | |
getData() | |
} | |
init () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment