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.
solved What is Promise in javascript? [duplicate]