by megous · 7y ago · 0 comments
let usersRange = (start, end, result, doneCb, errorCb) => {
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open('GET', 'http://jsonplaceholder.typicode.com/users/' + start)
xhr.send();
xhr.onerror = ev => errorCb();
xhr.onload = ev => {
result.push(xhr.response);
if (start < end)
return usersRange(start + 1, end, result, doneCb, errorCb);
done(result);
}
};
usersRange(0, 10, [], /* completion callbacks */);
Simpler, not really harder to read (half of it is just boilerplate around XHR setup, which is abstractable away). The meat of it is onload handler. const usersRange = async (start, end) => {
var result = [];
for (let current = start; current < end; current++) {
result.push(await fetch(`http://jsonplaceholder.typicode.com/users/${current}`).then(r => r.json())
}
return result;
} let usersRange = (start, end, result, done) => {
if (start == end)
return done(null, result);
GET('http://jsonplaceholder.typicode.com/users/' + start,
res => usersRange(start + 1, end, (result.push(res), result), done),
err => done(err)
)
};
GET() just wraps the XHR code in my original post and provides access to onload/onerror callbacks. I used XHR, to avoid using fetch/Promise, which is part of the pyramid.I mean, I prefer async/await. The point is that it's just not inherently that much more verbose to write callback based async code. Composition would be more complicated. You'd have to use some abstract helper methods, or nest the callbacks. For example:
chain(
(_, next) => usersRange(0, 10, [], next),
([err, res], next) => {
if (err)
// blabla
usersDoSomething(res),
}
)
vs: try {
let res = await usersRange(0, 10),
usersDoSomething(res),
} catch(ex) {
if (err)
// bla bla
}
You can do some pretty fun stuff with functions, extending JS syntax so it has simulated goto for example: let users = [], nextUser = 0;
labelledChain(
(_, next) => GET('/users', next),
'got-users', ([err, res], next) => {
users = res;
next();
},
'get-next-user', ([err, res], next) => {
if (users[nextUser])
GET('/users/' + users[nextUser].id, next);
else
doneCallback(null, users);
},
'got-next-user', ([err, res], next) => {
users[nextUser] = res;
nextUser++;
next.goto('get-next-user');
},
)
Fun challenge implementing labelledChain so that this all works. :DJavaScript has goto, it's the `continue` statement[1].
1: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
I have to admit, I didn't like promises and preferred node style callbacks until async/await and have been using it with babel since before the name change.
return nextUser(...
be return usersRange(... ?