CNode

关于request 嵌套request的问题,有没有好的解决方案

问答
Qqxl1231发布于10 年前最后回复10 年前3 回复4651 浏览0 收藏

试试水

request(options1, function (error, response, body) { var b=body.xx; options2=b; //b作为参数的一部分 request(options2, function (error, response, body2) { console.log(body2); }}

这种情况会报 Error: Can't set headers after they are sent.
原因我箱大家应该都知道, 这种嵌套肯定是不对的, 想用promise,但是苦于还没摸清楚它怎么玩,有没有大牛指点下

查看回复

回复 (3)

R
richenlin#1·10 年前

有个request-promise的包,就是request的promise封装

用法就简单了:

let reqp = require('request-promise');
return reqp(option1).then(body => {
	let option2 = body.xxx;
	return reqp(option2);
}).then(body2 => {
	console.log(body2);
}).catch(err => {
	console.log(err)
})
R
richenlin#2·10 年前

还能这样写(注意async/await是下一代标准里的语法,还未被支持,需要用babel等编译后才能运行):

let reqp = require('request-promise');
async function(){
	let body = await reqp(option1).catch(err => console.log(err));
	let body2 = await reqp(body.xxx).catch(err => console.log(err));
	console.log(body2);
}
Q
qxl1231#3·10 年前

嗯,好,不错不错,我试一下哈,

参与回复
登录后即可参与回复。登录