Skip to content

Instantly share code, notes, and snippets.

Created May 2, 2013 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/5504852 to your computer and use it in GitHub Desktop.
Save anonymous/5504852 to your computer and use it in GitHub Desktop.
Refactoring nested example to pure functions
Y.io.xhr = function (uri, options) {
options = options || {};
return new Y.Promise(function (resolve, reject) {
var io = Y.io(url, {
// reference options directly to avoid insertion of unwanted options
// into Y.io()
method: options.method,
data: options.data,
headers: options.headers,
form: options.form,
timeout: options.timeout,
on: {
success: function (id, response) {
resolve(response);
},
failure: function (id, response) {
reject(response);
}
}
});
// expose abort. It is not a prototype function so it's ok to copy it
this.abort = io.abort;
});
};
Y.io.getJSON = function (url, options) {
var promise = Y.io.xhr(url, options);
return Y.mix(promise.then(function (xhr) {
return Y.JSON.parse(xhr.responseText);
}), {
// pass around the abort function
abort: promise.abort
});
};
var getData = (function () {
function fetchData(offset) {
return Y.io.getJSON('/foo' + offset);
}
function concatData(dataset, offset) {
if (dataset.length < 100) {
offset += 100;
return fetchData(offset).then(function (newDataset) {
return concatData(dataset.concat(newDataset), offset);
});
} else {
return dataset;
}
}
return function getData(offset) {
return concatData([], offset);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment