Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Going async with generators
function main(generatorFn) {
let it = generatorFn();
/**
* @param {IteratorResult} p
*/
function resolver(p) {
if (p.done) {
return;
}
p.value.then(function(response) {
resolver(it.next(response));
}).catch(function(reason) {
it.throw(new Error(reason.error.message));
});
}
resolver(it.next());
}
function fetch(url, data) {
return new Promise(function(resolve, reject) {
let request = new XMLHttpRequest();
let method = typeof data === 'undefined' ? 'get' : 'post';
request.open(method, url);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
resolve(JSON.parse(request.response));
} else if (request.status >= 400) {
reject(JSON.parse(request.response));
}
}
}
request.send(method === 'post' ? JSON.stringify(data) : null);
});
}
main(function* () {
let result = yield fetch('https://api.spotify.com/v1/search?type=artist&q=opeth');
console.log(result.artists.items.map(i => i.name));
try {
let albums = yield fetch('https://api.spotify.com/v1/search?type=album');
} catch (e) {
console.log(e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.