javascript - Getting files over HTTP in Node using promises -
i wrote function fetches file url, taking redirects account:
const fetchfile = (url, successcallback, errorcallback) => { http.get(url).on('response', function(response) { var body = '' if((response.statuscode == 301) || (response.statuscode == 302)) { console.log('redirection ' + url + ' ' + response.headers.location + ' caught...') fetchfile(response.headers.location, successcallback, errorcallback) return } response.on('data', function(chunk) { body += chunk }) response.on('end', function() { console.log('completed!') successcallback(body) }) }) } this code seems work correctly, , trying rewrite use promises without external modules, i'm not making headway. came code:
const fetchfileprom = function(url) { console.log('in fetchfileprom()'); return new promise((resolve, reject) => { console.log('in promise function body') var req = http.get(url, (response) => { console.log('in response handler func body'); var body = '' if((response.statuscode == 301) || (response.statuscode == 302)) { console.log('redirection ' + url + ' ' + response.headers.location + ' caught...') return fetchfileprom(response.headers.location) } response.on('data', (fragment) => { body += fragment }) response.on('end', () => resolve(body) ) }) req.on('error', function(err) { reject(err) }) }) } when run this, in promise function body message nothing further that. doing wrong here?
when you're in asynchronous operation, regular return doesn't work when you're doing return fetchfileprom(response.headers.location), nothing takes care of return , there's nothing ever resolve promise.
what need recursively pass callbacks next asynchronous operation:
... var req = http.get(url, (response) => { console.log('in response handler func body'); var body = '' if((response.statuscode == 301) || (response.statuscode == 302)) { console.log('redirection ' + url + ' ' + response.headers.location + ' caught...') fetchfileprom(response.headers.location).then(resolve, reject); } else { response.on('data', (fragment) => { body += fragment }) response.on('end', () => resolve(body) ) } }) ...
Comments
Post a Comment