使用promises

时间:2017-09-12 13:37:56

标签: javascript node.js http promise es6-promise

我编写了这个函数,从URL中提取文件,将重定向考虑在内:

const fetchFile = (url, successCallback, errorCallback) => {
  http.get(url).on('response', function(response) {
    var body = ''
    if((response.statusCode == 301) || (response.statusCode == 302)) {
      console.log('Redirection for ' + url + ' to ' + 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)
    })
  })
}

这段代码似乎工作正常,现在我试图重写它以使用promises而不需要任何外部模块,但我没有取得多大进展。我想出了这段代码:

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 for ' + url + ' to ' + 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)
    })
  })
}

当我运行此操作时,我收到了In Promise function body消息,但仅此而已。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

当您进行异步操作时,常规-p无法正常工作,因此当您执行return时,没有任何事情可以处理该返回,并且#&# 39;什么都不会解决你的承诺。

您需要做的是递归地将回调传递给下一个异步操作:

return fetchFileProm(response.headers.location)