我正在开发一个不使用 jquery 的项目。所有受支持的浏览器都具有 native Promises。
我想复制 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})
如何使用原生 Promise 来做到这一点?
最佳答案
请尝试这个:
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);
});
关于javascript - 如何使用 native JavaScript Promise 执行延迟模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372638/