JavaScript are traditionally synchronous and execute from top to bottom. Callback Functions - When a function simply accepts another function as an argument, this contained function is known as a callback function. Using callback functions is a core functional programming concept, and you can find them in most JavaScript code; either in simple functions like setInterval .
setInterval[function() {
console.log('hello!');
}, 1000);
function introduction(firstName, lastName, callback) {
const fullName = `${firstName} ${lastName}`;
callback(fullName);
}
introduction('Chris','Nwamba', greeting);
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchrnous block of code to completely execute before other synchronous parts of the code can run. For instance, when making API requests to servers, we have no idea if these servers are offline or online, or how long it takes to process the server request.
With Promises, we can defer execution of a code block until an async request is completed. This way, other operations can keep running without interruption.
Promises have three states:
Pending: This is the initial state of the Promise before an operation begins
Fulfilled: This means the specified operation was completed
Rejected: The operation did not complete; an error value is usually thrown
The Promise object is created using the new keyword and contains the promise; this is an executor function which has a resolve and a reject callback
const promise = new Promise(function(resolve, reject) {
// promise description
})