1// *** JS GetPosts Callback ***
2
3 run.addEventListener('click', () => {
4 window.lib.getPosts((error, articles) => {
5 return (error ? console.log(error) : console.log(articles));
6 /* Alternate syntax
7 if (error) {
8 console.log(error);
9 }
10 for (elem of articles) {
11 console.log(elem);
12 }; // => console.log(articles); similarly works
13 /*
14 });
15 })
1/*
2A callback function is a function passed into another function
3as an argument, which is then invoked inside the outer function
4to complete some kind of routine or action.
5*/
6function greeting(name) {
7 alert('Hello ' + name);
8}
9
10function processUserInput(callback) {
11 var name = prompt('Please enter your name.');
12 callback(name);
13}
14
15processUserInput(greeting);
16// The above example is a synchronous callback, as it is executed immediately.
1function startWith(message, callback){
2 console.log("Clearly written messages is: " + message);
3
4 //check if the callback variable is a function..
5 if(typeof callback == "function"){
6 callback(); //execute function if function is truly a function.
7 }
8}
9//finally execute function at the end
10startWith("This Messsage", function mySpecialCallback(){
11 console.log("Message from callback function");
12})
1function greeting(name) {
2 alert('Hello ' + name);
3}
4
5function processUserInput(callback) {
6 var name = prompt('Please enter your name.');
7 callback(name);
8}
9
10processUserInput(greeting);
1// A function which accepts another function as an argument
2// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
3funct printANumber(int number, funct callbackFunction) {
4 printout("The number you provided is: " + number);
5}
6
7// a function which we will use in a driver function as a callback function
8funct printFinishMessage() {
9 printout("I have finished printing numbers.");
10}
11
12// Driver method
13funct event() {
14 printANumber(6, printFinishMessage);
15}
16
1// Create a callback in the probs, in this case we call it 'callback'
2function newCallback(callback) {
3 callback('This can be any value you want to return')
4}
5
6// Do something with callback (in this case, we console log it)
7function actionAferCallback (callbackData) {
8 console.log(callbackData)
9}
10
11// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
12function requestCallback() {
13 newCallback(actionAferCallback)
14}