4 ms·
Wow 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 fet
by BenoitEssiambre 6y ago
Wow 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);
...
});