Promises are used to simplify asynchronous programming.
Sometimes when writing a function, you don't know the value to return right away, quite often because you need to make an XMLHttpRequest
to get some data first.
Now you can return a Promise
which the function caller will use to get the value some time later.
new Promise(function(resolve, reject) { ... });
Here's a simple example:
function genNumber()
{
return new Promise(function (resolve, reject) {
var time = Math.random() * 3500 + 1000;
// Simulate some kind of async work
setTimeout(
function () {
return resolve(Math.round(time));
}, time);
// This simple example never rejects but you'd probably
// want to if you made a failing ajax call, for example.
});
}
// A Promise is returned here, not the number.
var p1 = genNumber();
Generally you'll then want to use then()
to do something with the value once it's ready.
// When the promise is resolved, we use the value
p1.then(function (value) {
console.log("Value from p1: " + value);
}, function () {
});
Another useful method is Promise.all(iterable)
. It's used to return a promise that resolves when all of the promises in the iterable have resolved. An "iterable" is an object such as an Array.
var p2 = genNumber();
var p3 = genNumber();
Promise.all([p1, p2, p3]).then(function (values) {
// This is executed when all the promises have resolved
console.log("Values from all(): " + values);
});
Promises are a fairly new but they already have some good support.
Hello, my name is Lee and I work as a full-stack web developer specialising in Microsoft ASP.NET technologies. I love using Umbraco and also MANAGED, my own application management software.
Contact me at lee.gunn@secretorange.co.uk
Get in touch to talk about your project or just ask me a question.