3

假设我有一个循环调用WinJS.xhr()多个地址。在响应处理程序中,有没有办法确定处理响应的地址?通过从传递给处理程序的 XmlHttpRequest 对象中辨别它xhr()还是通过手动传递其他东西?

我一直在查看文档并检查调试器中的响应,但找不到任何东西。

4

1 回答 1

4

我不认为响应中包含信息,但它不需要。每个 xhr 调用都有自己的 Promise,该 Promise 会针对该特定调用返回。我喜欢这样做...

//start with an array of some kind
var urls = [
    "http://something.com/1",
    "http://something.com/2",
    "http://something.com/3",
];

//map the array to a list of calls adding your url in so you have it
var results = urls.map(function(u) {
    return {url:u, response:WinJS.xhr({url:u})};
}

然后你可以循环结果数组,你就有了 url。您可能希望将其包装在另一个承诺中,以便整个事情是异步的。

function xhrCallsAsync() {

    //start with an array of some kind
    var urls = [
        "http://something.com/1",
        "http://something.com/2",
        "http://something.com/3",
    ];

    //map the array to a list of calls adding your url in so you have it
    var results = urls.map(function(u) {
        return {url:u, response:WinJS.xhr({url:u})};
    }

    //return a Promise that completes when all of the Promises are complete
    return WinJS.Promise.join(results);
}

希望有帮助!

于 2012-12-27T14:57:44.893 回答