如何使http.request 同步响应 - CNode技术社区

如何使http.request 同步响应
发布于 7 年前 作者 lh199507 3203 次浏览 来自 问答
function httpRequest(options) {
 return new Promise((resolve, reject)=> {
 try{
 const req = https.request(options, (res) => {
 // console.log('状态码:', res.statusCode);
 // console.log('请求头:', res.headers);
 res.on('data', (d) => {
 resolve(d);
 });
 });
 req.on('error', (e) => {
 console.error(e);
 reject(e)
 });
 req.end();
 }catch(e){
 console.log(e);
 }
 })
}
function main(index) {
 httpRequest(options).then(d=> {
 console.log(index);
 // process.stdout.write(d);
 })
}
for(let i=0;i<1000;i++){
 main(i);
}

这样使用因为是异步的,所以console.log(index)打印是不规则的。 怎么可以达到1,2,3,4.。。。1000的打印出来

4 回复
const fn = async () => {
	for (let i = 0; i < 1000; i++) {
		await main(i)
	}
}
fn()

试试看

试了一下 好像这样可以

async function main(){
	await httpRequest(options).then(d => {
 console.log(index);
 // process.stdout.write(d);
 })
}
const fn = async () => {
	for (let i = 0; i < 1000; i++) {
		await main(i)
	}
}
fn()

可以,解决了

let buffer = new Buffer(0); res.on(‘data’,function(chunk){ buffer = Buffer.concat(buffer,chunk); }); res.on(‘end’,function(){ resolve(buffer.toString(‘utf8’)); }); 当返回的数据量比较大的时候,res 的 data事件会触发多次;res的end事件只会在数据接收完毕的时候才触发,所以resolve需要在res.on(‘end’)的时候再调用就好了,chunk数据是buffer,所以最好使用buffer接收,避免出现乱码或者文件保存错误,最终再根据res.headers里面的content-type进行数据解析,看是属于文件还是JSON或xml之类的。调用就用上面的,没毛病~

回到顶部

AltStyle によって変換されたページ (->オリジナル) /