Skip to content

Instantly share code, notes, and snippets.

@dzek69
Created July 16, 2017 19:41
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 dzek69/b551c21504093ff7d91772c8967c07e5 to your computer and use it in GitHub Desktop.
Save dzek69/b551c21504093ff7d91772c8967c07e5 to your computer and use it in GitHub Desktop.
promise test
const log = (text) => {
if (text instanceof Error) {
text = "ERROR: " + text.message;
}
document.querySelector("#log").textContent += "\n" + JSON.stringify(text, null, 4);
}
const randomTime = () => Math.round(Math.random() * 1000);
const notNull = item => item !== null;
const getThumb = function(id) {
if (id === 3) {
return null;
}
return "http://some.link/image-" + id + ".jpg";
}
const getThumbAsync = function(id) {
return new Promise((resolve, reject) => {
if (id === 3) {
reject(new Error("cant get thumb"));
return;
}
if (id === 4) {
resolve("http://async-" + id + ".jpg");
return;
}
setTimeout(() => resolve("http://async-" + id + ".jpg"), randomTime());
});
}
const ids = [1, 2, 3, 4];
const getThumbs = (items) => {
return items.map(getThumb).filter(notNull);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment