承诺的请求没有 return resolve 的正确结果
Promisified request does not return the proper result on resolve
我正在尝试将 request
与 Bluebird 的 Promises
结合使用:
const request = Promise.promisify(require('request'));
Promise.promisifyAll(request);
不幸的是,我得到的结果并没有反映我基于示例的预期:
request('http://google.com').then(function(content) {
// content !== String
// Object.keys(content) => ['0', '1']
};
- 内容不是字符串
- 我必须分别通过
content['0']
访问内容 content['1']
而这里是我实际预期的响应,HTML 字符串是。
这对我来说似乎很可疑,就像我在这里滥用了 Promise API。我做错了什么?
使用 .spread(function(response, content){})
代替 .then(function(content){})
。
为什么不使用 native node 的 Promises?
function req() {
return new Promise (function(resolve, reject){
request('http://google.com',function (error, response, body){
if (error)
reject(error);
resolve(body) //if json, JSON.parse(body) instead of body
});
});
}
req().then(data => doSomethingWithData);
您应该使用 spread() 而不是 then()。
这里有一个bluebird的link,解释了spread()的用法。
request的所有回调函数都是由三个参数(err,response,content)组成。在 promisifed 请求中,err 由 catch() 处理。
但是如何将另外两个参数传递给下一个链式回调函数呢?它无法通过 then() 实现。
所以 promisifed 请求将 return 两个承诺的数组,一个将 return repsonse 和另一个 content.它们可以被 spread() 方法捕获,该方法能够捕获固定大小的承诺数组。
我正在尝试将 request
与 Bluebird 的 Promises
结合使用:
const request = Promise.promisify(require('request'));
Promise.promisifyAll(request);
不幸的是,我得到的结果并没有反映我基于示例的预期:
request('http://google.com').then(function(content) {
// content !== String
// Object.keys(content) => ['0', '1']
};
- 内容不是字符串
- 我必须分别通过
content['0']
访问内容content['1']
而这里是我实际预期的响应,HTML 字符串是。
这对我来说似乎很可疑,就像我在这里滥用了 Promise API。我做错了什么?
使用 .spread(function(response, content){})
代替 .then(function(content){})
。
为什么不使用 native node 的 Promises?
function req() {
return new Promise (function(resolve, reject){
request('http://google.com',function (error, response, body){
if (error)
reject(error);
resolve(body) //if json, JSON.parse(body) instead of body
});
});
}
req().then(data => doSomethingWithData);
您应该使用 spread() 而不是 then()。 这里有一个bluebird的link,解释了spread()的用法。
request的所有回调函数都是由三个参数(err,response,content)组成。在 promisifed 请求中,err 由 catch() 处理。
但是如何将另外两个参数传递给下一个链式回调函数呢?它无法通过 then() 实现。
所以 promisifed 请求将 return 两个承诺的数组,一个将 return repsonse 和另一个 content.它们可以被 spread() 方法捕获,该方法能够捕获固定大小的承诺数组。