Skip to content

Instantly share code, notes, and snippets.

@emartinez-usgs
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emartinez-usgs/10785128 to your computer and use it in GitHub Desktop.
Save emartinez-usgs/10785128 to your computer and use it in GitHub Desktop.
Asynchronous Javascript Development
var getContent = function () {
return 'Hello World!';
};
console.log(getContent()); // 'Hello World!'
var getContent = function (callback) {
callback('Hello World!');
};
getContent(console.log); // 'Hello World!'
var getContent = function (callback) {
Xhr.ajax({
url: 'hello.txt',
success: callback,
error: function () {
// Whoa error!
}
});
};
getContent(console.log); // 'Hello World!'
var getContent = function () {
return new Promise(function (fulfill, reject) {
Xhr.ajax({
url: 'hello.txt',
success: fulfill,
error: reject
});
});
};
getContent().then(console.log);
var getContent = function () {
return new Promise(function (fulfill, reject) {
Xhr.ajax({
url: 'noexist.txt',
success: fulfill,
error: function (error, xhr) {
reject(error + ': ' + xhr.statusText);
}
});
});
};
getContent()
.then(console.log)
.catch(console.log)
.then(function () {
console.log('Complete!');
});
var files = ['file1.txt', 'file2.txt', 'file3.txt'];
var getContent = function (url) {
return new Promise(function (fulfill, reject) {
Xhr.ajax({
url: url,
success: fulfill,
error: reject
});
});
};
Promise.all(files.map(getContent))
.then(function (values) {
values.forEach(console.log);
})
.catch(console.log)
.then(function () {
console.log('Complete!');
});
<!-- Placeholder Gist for Name Only -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment