如何使用本机 JavaScript 承诺执行延迟模式

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

本文关键字:执行 延迟 模式 承诺 JavaScript 何使用 本机      更新时间:2023-09-26

我正在做一个不使用jquery的项目。所有支持的浏览器都具有原生承诺。

我想复制jquery通过$提供的延迟模式。递 延

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

我怎样才能用本地承诺来做到这一点?

请尝试以下操作:

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/