2016-07-14 52 views
0

我正在開發一個不使用jquery的項目。所有支持的瀏覽器都具有原生Promise。如何使用原生JavaScript承諾做延期模式?

我想複製這種jQuery的通過$ .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}) 

提供的遞延模式如何能做到這一點與本機的承諾?

+0

那些deffereds的承諾。以相同的方式使用它們。但似乎你需要創建自己的get會使用承諾 - http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promisifying-xmlhttprequest – llamerr

回答

2

請試試這個:

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

演示:https://jsfiddle.net/iRbouh/52xxjhwu/

+0

一些解釋會很好。否則,很好的答案! – Pavlo

+1

我已經評論過該代碼,請查看;) –