关于request 嵌套request的问题,有没有好的解决方案
发布于 8 年前 作者 qxl1231 3910 次浏览 来自 问答

试试水

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 回复

有个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)
})

还能这样写(注意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);
}

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

回到顶部