Establecer valores de tiempo de espera con WinJS.xhr o HttpClient (HTML)

[ Este artículo está destinado a desarrolladores de Windows 8.x y Windows Phone 8.x que escriben aplicaciones de Windows en tiempo de ejecución. Si estás desarrollando para Windows 10, consulta la documentación más reciente

Al usar XMLHttpRequest, puedes establecer valores de tiempo de espera directamente, algo que no es posible con Windows.Web.Http.HttpClient o WinJS.xhr. Sin embargo, existe un modo de establecer tiempos de espera en objetos WinJS.Promise. Al llamar a WinJS.Promise.timeout, harás que la solicitud se cancele si no se completa dentro del intervalo de tiempo especificado.

En el código del proyecto XhrExample creado en Cómo descargar un archivo con WinJS.xhr, encapsula el método WinJS.xhr en una llamada a WinJS.Promise.timeout.

Ten en cuenta que al usar WinJS.Promise.timeout de este modo, debes usar then, que devuelve Promise cuando se produce un error, en lugar de done, que no lo hace.

var xhrDiv = document.getElementById("xhrReport");

WinJS.Promise.timeout(1500, WinJS.xhr({ url: "https://www.microsoft.com" })
    .then(function complete(result) {
        xhrDiv.innerText = "Downloaded the page";
        xhrDiv.style.backgroundColor = "#00FF00";
        },
        function error(error){
            // The error thrown when xhr is canceled has a message property, not a statusText property.
            if (error.statusText)
                xhrDiv.innerHTML = "Got error: " + error.statusText;
            else
                xhrDiv.innerHTML = "Got error: " + error.message;
            xhrDiv.style.color = "#000000";
            xhrDiv.style.backgroundColor = "#FF0000";
        },
        function progress(result) {
            xhrDiv.innerText = "Ready state is " + result.readyState;
            xhrDiv.style.color = "#000000";
            xhrDiv.style.backgroundColor = "#0000FF";
    }));

Cuando ejecutas este código, la solicitud web debe completarse sin errores y el elemento DIV debe verse en verde. Para ver lo que sucede cuando se cancela la solicitud, acorta el período de tiempo de espera a 200 milisegundos:

var xhrDiv = document.getElementById("xhrReport");

WinJS.Promise.timeout(200, WinJS.xhr({ url: "https://www.microsoft.com" })
    .then(function complete(result) {
        xhrDiv.innerText = "Downloaded the page";
        xhrDiv.style.backgroundColor = "#00FF00";
        },
        function error(error){
            // The error thrown when xhr is canceled has a message property, not a statusText property.
            if (error.statusText)
                xhrDiv.innerHTML = "Got error: " + error.statusText;
            else
                xhrDiv.innerHTML = "Got error: " + error.message;
            xhrDiv.style.color = "#000000";
            xhrDiv.style.backgroundColor = "#FF0000";
        }));

En este caso, la solicitud web debe cancelarse. El elemento DIV debe tornarse rojo y debe aparecer el mensaje "Error: cancelada".

Si usamos el código del proyecto XhrExample también podemos mostrar cómo establecer un tiempo de espera cuando se usa Windows.Web.Http.HttpClient.

var xhrDiv = document.getElementById("xhrReport");

var hc = new Windows.Web.Http.HttpClient();
var uri = new Windows.Foundation.Uri("https://www.microsoft.com");
WinJS.Promise.timeout(1500, hc.getAsync(uri)
    .then(function complete(result) {
        xhrDiv.innerText = "Downloaded the page:";
        xhrDiv.style.backgroundColor = "#009900"; // Set to dark green.
        result.content.readAsStringAsync().then(function complete(str) {
            xhrDiv.innerText += "Content:" + str;
            xhrDiv.style.backgroundColor = "#00FF00"; // Set to light green.
        })
    },
        function error(error) {
            // The error thrown when xhr is canceled has a message property, not a statusText property.
            if (error.statusText)
                xhrDiv.innerHTML = "Got error: " + error.statusText;
            else
                xhrDiv.innerHTML = "Got error: " + error.message;
            xhrDiv.style.color = "#000000";
            xhrDiv.style.backgroundColor = "#FF0000";
        },
        function progress(result) {
            xhrDiv.innerText = "Ready state is " + result.readyState;
            xhrDiv.style.color = "#000000";
            xhrDiv.style.backgroundColor = "#0000FF";
        }));

Temas relacionados

Otros recursos

Conexión a servicios web

Cómo descargar un archivo con WinJS.xhr

Cómo cargar datos binarios con WinJS.xhr

Referencia

Windows.Foundation.Uri

Windows.Web.Http

Windows.Web.Http.HttpClient

WinJS.xhr

XMLHttpRequest

Mejoras de XMLHttpRequest

Muestras

Muestra de HttpClient

Integrar contenido y controles de una muestra de servicios web

Muestra del uso de un blob para guardar y cargar contenido

Muestra de autenticación web

XHR, control de errores de navegación y muestra de esquemas de direcciones URL