function getMchArr(){ const options = { hostname: 'localhost.manage.donotcall.com.cn', port: 80, path: '/ZhouBaoApi/GetConditionMch?start_time=20230522&end_time=20230528&avg_num=3000000', method: 'GET' }; var mch_arr = []; const req = http.request(options, (res) => { res.on('data', (chunk) => { var result = chunk.toString(); var result = JSON.parse(result); for (let i = 0; i < result.data.length; i++) { const item = result.data[i]; mch_arr.push(item.mch_id) console.log(1111) } }); }); req.on('error', (error) => { console.error(error); }); req.end(); console.log(222) return mch_arr; }1111还没打印出来就打印了222,怎么让他顺序执行
时间: 2024-03-08 10:50:02 浏览: 16
要让这段代码按照顺序执行,可以将返回 `mch_arr` 的操作放到请求响应的回调函数中,这样就可以等到请求返回后再返回 `mch_arr`。例如,可以将代码改为:
```
function getMchArr(callback) {
const options = {
hostname: 'localhost.manage.donotcall.com.cn',
port: 80,
path: '/ZhouBaoApi/GetConditionMch?start_time=20230522&end_time=20230528&avg_num=3000000',
method: 'GET'
};
var mch_arr = [];
const req = http.request(options, (res) => {
res.on('data', (chunk) => {
var result = chunk.toString();
var result = JSON.parse(result);
for (let i = 0; i < result.data.length; i++) {
const item = result.data[i];
mch_arr.push(item.mch_id)
console.log(1111)
}
callback(mch_arr); // 在请求回调函数中返回 mch_arr
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();
}
getMchArr((mch_arr) => { // 调用 getMchArr 并在回调函数中处理返回的 mch_arr
console.log(mch_arr);
});
```
这样,当调用 `getMchArr` 时,它会发起一个 HTTP GET 请求,请求返回后会执行回调函数,并将 `mch_arr` 作为参数传入。在回调函数中,可以对 `mch_arr` 进行处理,例如打印出来。