用蓝鸟实现request.postAsync承诺

我正在使用bluebird promises框架来发出POST请求并获得对该POST请求的响应:

var Promise = require('bluebird'); var request = Promise.promisifyAll(require('request')); // Set the headers var headers = { 'User-Agent': 'Super Agent/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' } var options = []; var scores = []; // Configure the request options[0] = { url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1', method: 'POST', headers: headers, form: {'apikey': 'XXXXXXXXXXX', 'text': 'I love dogs'} } // Start the request request.postAsync(options[0]).spread(function(response, body) { if (response.statusCode == 200) { var answer = JSON.parse(body); scores[0] = answer['aggregate']['score']; } }).then(function() { console.log(scores[0]) }); 

这是我得到的错误信息:

 Unhandled rejection TypeError: expecting an array or an iterable object but got [object Null] at apiRejection (/Users/vphuvan/demos/node_modules/bluebird/js/release/promise.js:10:27) etc. 

我需要做什么来解决这个错误信息?

注意:我目前使用的蓝鸟版本是3.0.5

您需要在bluebird 3中设置multiArgs: true 。这是bluebird 3 promisify API中的一个变化。

以下完整解决scheme

 var Promise = require('bluebird'); var request = Promise.promisifyAll(require('request'), { multiArgs: true }); // Set the headers var headers = { 'User-Agent': 'Super Agent/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' } var options = []; var scores = []; // Configure the request options[0] = { url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1', method: 'POST', headers: headers, form: {'apikey': 'XXXXXXXXXXX', 'text': 'I love dogs'} } // Start the request request.postAsync(options[0]).spread(function(response, body) { if (response.statusCode == 200) { var answer = JSON.parse(body); scores[0] = answer['aggregate']['score']; } }).then(function() { console.log(scores[0]) }); 

这是一个有效的答案:使用'request-promise'框架。 我正在使用request-promise@1.0.2,它基于bluebird@2.10.2。 显然,在bluebird@2.10.2和bluebird@3.0.5之间发生了一些没有logging的事情

 var rp = require('request-promise'); // Set the headers var headers = { 'User-Agent': 'Super Agent/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' } var options = []; var scores = []; var text = 'I love dogs'; // Configure the request options[0] = { url: 'https://api.havenondemand.com/1/api/sync/analyzesentiment/v1', method: 'POST', headers: headers, form: {'apikey': 'XXXXXXXXXX', 'text': text} } // Start the request rp(options[0]) .then(function (body) { // POST succeeded... console.log(body); var answer = JSON.parse(body); scores[0] = answer['aggregate']['score']; }) .then(function() { console.log(scores[0]); }) .catch(function (err) { throw err });