如何正确编写promise返回函数?

时间:2015-11-24 23:09:32

标签: javascript promise bluebird

我尝试按照承诺返回模式编写函数,这是我尝试的一个通用示例:

var Promise = require('bluebird');
var request = require('request');

var returnPromise = Promise.method(function () {
    request
      .get('http://google.com/img.png')
      .on('response', function(response) {
            if (response.statusCode !== 200)
                throw new Error('Bad request');

            else
                return response.headers;
      })    
});

returnPromise()
    .then(function (headers) {
        console.log(headers);
    })
    .catch(function (err) {
        console.log('Error handling);
    });

然而,由于错误仍然被抛出而未被处理,因此无法正常工作。该如何实施?

2 个答案:

答案 0 :(得分:2)

var Promise = require('bluebird');
var request = require('request');

var returnPromise = function () {
  return new Promise(function(resolve, reject){
    request
      .get('http://google.com/img.png')
      .on('response', resolve)
      .on('error', reject) 
  });
});

答案 1 :(得分:1)

您应该使用new Promise而不是Promise.method。这是因为承诺不会从事件处理程序中抛出或返回。

var Promise = require('bluebird');
var request = require('request');

var returnPromise = function () {
  return new Promise(function(resolve, reject){
    request
      .get('http://google.com/img.png')
      .on('response', function(response) {
            if (response.statusCode !== 200)
                reject(Error('Bad request'));

            else
                resolve(response.headers);
      })    
  });
});

returnPromise()
    .then(function (headers) {
        console.log(headers);
    })
    .catch(function (err) {
        console.log('Error handling);
    });