-6

Before posing this question I have researched lots of related Promise on MDN.

Can you please explain to me in a simple word like

  1. What is Promise?
  2. How and when to use?
  3. Any simple example
Devang
  • 454
  • 1
  • 8
  • 18

2 Answers2

1

Quoting MDN:

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Basically, if you have some synchronous code (eg. alert()), and you needed to use an asynchronous function (eg. setTimeout()), you could use a promise (as shown on the first example).

Here is the example:

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

console.log(promise1);
// expected output: [object Promise]

Use it to combine synchronous code with asynchronous code.

Community
  • 1
  • 1
Samyok Nepal
  • 535
  • 3
  • 15
-3

It is very simple thing. Promise is good for async operation. You can take example of Q.js and Promise.js.

Deepak Kumar
  • 648
  • 6
  • 14