spinners
spinners

Reputation: 2679

How do I do a deferred pattern with native javascript promises?

I'm working on a project that does not use jquery. All the supported browsers feature native Promises.

I would like to replicate the deferred pattern that jquery provided via $.Deferred

//Example
var deferred1 = new $.Deferred();
var deferred2 = new $.Deferred();

$.get(someUrl, function(){
  ...
  deferred1.resolve()
})

$.get(someUrl, function(){
  ...
  deferred2.resolve()
})

$.when(deferred1, deferred2).then(function(){//do stuff})

How can I do this with native promises?

Upvotes: 0

Views: 642

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

Please try this:

function get(url) {
    //Make and return new promise, it takes a callback: 
    //A function that will be passed other functions via the arguments resolve and reject
    return new Promise((resolve, reject) => {
        var request = new XMLHttpRequest();
        request.addEventListener("load", () => {
            //Success ! we need to resolve the promise by calling resolve.
            resolve(request.responseText);
        });
        request.addEventListener("error", () => {
            //Error! we need to reject the promise by calling reject .
            reject(request.statusCode);
        });
        //Perform the request
        request.open('GET', url);
        request.send();
    });
};

var urls = [
        'https://httpbin.org/ip',
        'https://httpbin.org/user-agent'
];
//Create an array of promises
// is equivalent to 
//var promises = []; for(var i in urls) promises.push(get(url[i]));
var promises  = urls.map(get);

//The Promise.all(iterable) method returns a promise that resolves when 
//all of the promises in the iterable argument have resolved, 
//or rejects with the reason of the first passed promise that rejects.
Promise.all(promises).then(function (responses) {
     console.log(responses);
});

Demo: https://jsfiddle.net/iRbouh/52xxjhwu/

Upvotes: 1

Related Questions