Infosys Interview Question

Difference between call back function and promise?

Interview Answers

Anonymous

Nov 3, 2022

A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise.

Anonymous

Apr 30, 2019

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 })

1