3 ms·
So generators are used here because of the natural way of calling “next” and yielding a result. How would this work for say, an XMLHttpRequest? Since you have
by no_wizard 7y ago
So generators are used here because of the natural way of calling “next” and yielding a result.
How would this work for say, an XMLHttpRequest? Since you have to next into callbacks there I don’t think yield travels the function boundary...so you abuse next instead?
- BenoitEssiambre 7y agoWow I haven't used that directly in a long time. Ideally you would wrap it to be in continuation passing style. This would look something like: function fetchUrl(url,done){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 400)) { done(null,xhr.responseText); }else{ done(new Error("something went wrong")) } } } xhr.open('GET', url, true); xhr.send(null); } Then you could do: let response=yield fetchUrl('http://example.com',next); edit: In case this doesn't really answer the question: If you really don't want to wrap, it would work inline too. It would just be harder to read and follow: var someFunction =casync(function*(url,next){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 400)) { next(null,xhr.responseText); }else{ next(new Error("something went wrong")) } } } xhr.open('GET', url, true); var response = yield xhr.send(null); ... });