refactor(main): 重构主函数并添加日志记录功能
- 新增 log 和 error 函数用于日志记录 - 重新封装 HTTP 请求和 API 处理逻辑 - 主函数增加错误处理和任务完成检查 - 添加定时器实现循环执行
This commit is contained in:
parent
431267228f
commit
0ac201e93b
198
main.js
198
main.js
|
@ -1,81 +1,155 @@
|
||||||
function promiseHttpLibGet(url) {
|
// ========== 日志写入文件的封装 ==========
|
||||||
return new Promise((resolve, reject) => {
|
function log(...args) {
|
||||||
http.get(url, {}, (res, err) => {
|
const message = `[LOG] ${args.map(a =>
|
||||||
if (err) {
|
typeof a === 'object' ? JSON.stringify(a) : a
|
||||||
reject(err);
|
).join(' ')}`;
|
||||||
} else {
|
console.log(message);
|
||||||
resolve(res);
|
files.append("/sdcard/output_log.txt", new Date().toISOString() + " " + message + "\n");
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
function error(...args) {
|
||||||
|
const message = `[ERROR] ${args.map(a =>
|
||||||
|
typeof a === 'object' ? JSON.stringify(a) : a
|
||||||
|
).join(' ')}`;
|
||||||
|
console.error(message);
|
||||||
|
files.append("/sdcard/output_log.txt", new Date().toISOString() + " " + message + "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 网络请求封装 ==========
|
||||||
|
function httpGetWithCallbacks(url, successCallback, errorCallback) {
|
||||||
|
http.get(url, {}, (res, err) => {
|
||||||
|
if (err) {
|
||||||
|
if (errorCallback) errorCallback(err);
|
||||||
|
} else {
|
||||||
|
if (successCallback) successCallback(res);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function processIpApi(url, successCallback, errorMsgPrefix) {
|
function processIpApiWithCallbacks(url, processSuccessCallback, errorMsgPrefix, apiDoneCallback) {
|
||||||
try {
|
httpGetWithCallbacks(url,
|
||||||
const res = await promiseHttpLibGet(url); // 使用 await等待Promise结果
|
(res) => {
|
||||||
|
let operationSuccessful = false;
|
||||||
|
if (!res) {
|
||||||
|
toast(errorMsgPrefix + "请求没有返回有效响应");
|
||||||
|
log(errorMsgPrefix + "请求没有返回有效响应");
|
||||||
|
if (apiDoneCallback) apiDoneCallback(new Error("No valid response from request (res is null)"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.statusCode != 200) {
|
||||||
|
let errorBody = "";
|
||||||
|
try {
|
||||||
|
if (res.body && typeof res.body.string === 'function') {
|
||||||
|
errorBody = res.body.string(); // 读取并关闭
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
error(errorMsgPrefix + "读取错误响应体失败: ", e);
|
||||||
|
}
|
||||||
|
toast(errorMsgPrefix + "获取失败,状态码: " + res.statusCode);
|
||||||
|
log(errorMsgPrefix + "获取失败,状态码: " + res.statusCode + ", Body: " + errorBody);
|
||||||
|
if (apiDoneCallback) apiDoneCallback(new Error(errorMsgPrefix + "获取失败,状态码: " + res.statusCode));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (res && res.statusCode == 200) {
|
|
||||||
try {
|
try {
|
||||||
let data = res.body.json();
|
let data = res.body.json(); // 读取并关闭
|
||||||
successCallback(data);
|
processSuccessCallback(data);
|
||||||
|
operationSuccessful = true;
|
||||||
} catch (jsonError) {
|
} catch (jsonError) {
|
||||||
toast(errorMsgPrefix + "解析JSON失败");
|
toast(errorMsgPrefix + "解析JSON失败");
|
||||||
console.error(errorMsgPrefix + "解析JSON失败: ", jsonError);
|
error(errorMsgPrefix + "解析JSON失败: ", jsonError);
|
||||||
if (res.body && typeof res.body.string === 'function') {
|
if (apiDoneCallback) apiDoneCallback(jsonError);
|
||||||
console.log("原始响应体: ", res.body.string());
|
return;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if (res) {
|
|
||||||
toast(errorMsgPrefix + "获取失败,状态码: " + res.statusCode);
|
if (apiDoneCallback) apiDoneCallback(null);
|
||||||
console.log(errorMsgPrefix + "获取失败,状态码: " + res.statusCode);
|
},
|
||||||
if (res.body && typeof res.body.string === 'function') {
|
(requestError) => {
|
||||||
console.log("原始响应体: ", res.body.string());
|
error(errorMsgPrefix + "处理时发生错误: ", requestError);
|
||||||
|
if (!toast.isShow()) {
|
||||||
|
toast(errorMsgPrefix + "请求或处理失败");
|
||||||
}
|
}
|
||||||
} else {
|
if (apiDoneCallback) apiDoneCallback(requestError);
|
||||||
toast(errorMsgPrefix + "请求没有返回有效响应");
|
|
||||||
console.log(errorMsgPrefix + "请求没有返回有效响应");
|
|
||||||
}
|
}
|
||||||
} catch (requestError) {
|
);
|
||||||
console.error(errorMsgPrefix + "请求失败: ", requestError);
|
|
||||||
toast(errorMsgPrefix + "请求失败,请检查网络");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
// ========== 主函数 ==========
|
||||||
// 并行发起两个请求
|
function main() {
|
||||||
const countryPromise = processIpApi("https://ipv4.geojs.io/v1/ip/country.json", function(data2){
|
log("Main function started.");
|
||||||
toast("国家代码: " + data2.country);
|
|
||||||
console.log("地理位置信息:");
|
|
||||||
console.log("国家代码 (2位): " + data2.country);
|
|
||||||
console.log("国家代码 (3位): " + data2.country_3);
|
|
||||||
console.log("IP 地址: " + data2.ip);
|
|
||||||
console.log("国家名称: " + data2.name);
|
|
||||||
}, "地理位置");
|
|
||||||
|
|
||||||
const geoPromise = processIpApi("https://ipv4.geojs.io/v1/ip/geo.json", function(data3){
|
let tasksCompleted = 0;
|
||||||
console.log("新增接口返回的地理数据:");
|
const totalTasks = 2;
|
||||||
console.log("经度: " + data3.longitude);
|
let errors = [];
|
||||||
console.log("纬度: " + data3.latitude);
|
|
||||||
console.log("城市: " + data3.city);
|
|
||||||
console.log("地区: " + data3.region);
|
|
||||||
console.log("国家: " + data3.country);
|
|
||||||
console.log("组织名称: " + data3.organization_name);
|
|
||||||
console.log("IP 地址: " + data3.ip);
|
|
||||||
console.log("国家代码 (2位): " + data3.country_code);
|
|
||||||
console.log("国家代码 (3位): " + data3.country_code3);
|
|
||||||
console.log("时区: " + data3.timezone);
|
|
||||||
console.log("ASN: " + data3.asn);
|
|
||||||
console.log("洲: " + data3.continent_code);
|
|
||||||
}, "详细地理位置");
|
|
||||||
|
|
||||||
// 等待两个请求完成(或失败)
|
function checkAllTasksDone() {
|
||||||
try {
|
tasksCompleted++;
|
||||||
await Promise.all([countryPromise, geoPromise]);
|
if (tasksCompleted === totalTasks) {
|
||||||
} catch (error) {
|
log("All API calls have finished processing.");
|
||||||
console.error("一个或多个API请求失败:", error);
|
if (errors.length > 0) {
|
||||||
|
error("One or more API calls failed:");
|
||||||
|
errors.forEach(err => error(err));
|
||||||
|
toast("部分API请求失败,请检查日志");
|
||||||
|
} else {
|
||||||
|
log("All API calls were successful.");
|
||||||
|
toast("所有API请求成功");
|
||||||
|
}
|
||||||
|
log("Script operations concluded. Adding a small delay for UI.");
|
||||||
|
sleep(500);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleApiError(error) {
|
||||||
|
if (error) {
|
||||||
|
errors.push(error);
|
||||||
|
}
|
||||||
|
checkAllTasksDone();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用第一个 API
|
||||||
|
processIpApiWithCallbacks(
|
||||||
|
"https://ipv4.geojs.io/v1/ip/country.json",
|
||||||
|
function(data2) {
|
||||||
|
toast("国家代码: " + data2.country);
|
||||||
|
log("地理位置信息:");
|
||||||
|
log("国家代码 (2位): " + data2.country);
|
||||||
|
log("国家代码 (3位): " + data2.country_3);
|
||||||
|
log("IP 地址: " + data2.ip);
|
||||||
|
log("国家名称: " + data2.name);
|
||||||
|
},
|
||||||
|
"地理位置",
|
||||||
|
handleApiError
|
||||||
|
);
|
||||||
|
|
||||||
|
// 调用第二个 API
|
||||||
|
processIpApiWithCallbacks(
|
||||||
|
"https://ipv4.geojs.io/v1/ip/geo.json",
|
||||||
|
function(data3) {
|
||||||
|
log("新增接口返回的地理数据:");
|
||||||
|
log("经度: " + data3.longitude);
|
||||||
|
log("纬度: " + data3.latitude);
|
||||||
|
log("城市: " + data3.city);
|
||||||
|
log("地区: " + data3.region);
|
||||||
|
log("国家: " + data3.country);
|
||||||
|
log("组织名称: " + data3.organization_name);
|
||||||
|
log("IP 地址: " + data3.ip);
|
||||||
|
log("国家代码 (2位): " + data3.country_code);
|
||||||
|
log("国家代码 (3位): " + data3.country_code3);
|
||||||
|
log("时区: " + data3.timezone);
|
||||||
|
log("ASN: " + data3.asn);
|
||||||
|
log("洲: " + data3.continent_code);
|
||||||
|
},
|
||||||
|
"详细地理位置",
|
||||||
|
handleApiError
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== 启动主函数并设置定时器 ==========
|
||||||
|
|
||||||
|
(function startLoop() {
|
||||||
|
const intervalMillis = 60 * 1000; // 每隔 60 秒执行一次
|
||||||
|
|
||||||
main(); // 执行主函数
|
main(); // 首次启动
|
||||||
|
setInterval(main, intervalMillis); // 循环执行
|
||||||
|
})();
|
||||||
|
|
Loading…
Reference in New Issue