Last active
August 29, 2015 14:16
-
-
Save yuchi/2c8ac06115f29d1d1abc to your computer and use it in GitHub Desktop.
Multiple requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = doRequest; | |
function doRequest(url, callback) { | |
var client = Ti.Network.createHTTPClient({}); | |
client.onerror = function (err) { | |
callback(err, null); | |
} | |
client.onload = function () { | |
try { | |
callback(null, JSON.stringify(this.responseText)); | |
} | |
catch (err) { | |
callback(err, null); | |
} | |
} | |
client.open('GET', url); | |
client.send(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var doRequest = require('APIs'); | |
var urls = [ 'http://www.1.com', 'http://www.2.com' ]; | |
allOrNothing(urls, function (err, results) { | |
if (err) return alert(err + ''); | |
var win = Ti.UI.createWindow({ | |
title: 'prova' | |
}); | |
results.forEach(function (result) { | |
alert(JSON.stringify(result, null, 2)); | |
}); | |
}); | |
// Questo codice lancia le richieste in contemporanea, e | |
// qualora una delle richieste fallisca l’errore che ha | |
// generato viene passato alla `callback` e il risultato | |
// delle altre richieste scartato. | |
// | |
// ATTENZIONE! Utilizzare solo con metodi ‘read’ (GET, | |
// HEAD, OPTIONS etc) perché non puoi sapere se le altre | |
// richieste sono andate a buon fine. | |
// | |
// Callback è Function<Error, Array<results>>. | |
function allOrNothing(urls, callback) { | |
var failed = false; | |
var finished = false; | |
var counter = 0; | |
var results = new Array(params.length); | |
function fail(err) { | |
failed = true; | |
callback(err, null); | |
} | |
function success(result, index) { | |
results[ index ] = result; | |
counter += 1; | |
if (counter >= params.length) { | |
finished = true; | |
callback(null, results); | |
} | |
} | |
urls.forEach(function (url, index) { | |
doRequest(url, function (err, result) { | |
if (failed) return; | |
if (finished) return; | |
if (err) fail(err); | |
else success(result, index); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment