我正在使用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.
我必须怎么做才能解决此错误消息?
注意:我当前使用的bluebird的版本是3.0.5
最佳答案
您需要在bluebird 3中设置multiArgs: true
。这是bluebird 3 promisify API中的更改之一。
完整解决方案如下。
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]) });
关于node.js - 用bluebird实现request.postAsync promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33565210/