javascript - 如何使用 async GM_xmlhttpRequest 以原始顺序返回值?
问题描述
我正在尝试制作一个 Tampermonkey 脚本来更新某些网站上的日期。我从一个站点获得了一个 id 数组,并且我正在使用该数组的 id 从它请求数据。之后,我必须返回每个输入的数据。
由于函数是async
,它以随机顺序返回数据,但我需要这些新数组以原始顺序返回。我试过sync和Promise
s,但是第一个太慢了,第二个没看懂。
我可以对 id 进行排序,但我也得到了按第一个数组顺序排列的日期,所以我不知道如何实现与第二个 id 数组相同的顺序。
这是代码:
id = GM_getValue('id');
for (let i = 0; i < id.length; i++) {
setTimeout(() => {
console.log("Updating " + (i + 1) + " Title");
GM_xmlhttpRequest({
method: "GET",
url: "***" + id[i] + "/***",
onload: function(response) {
$(response.responseText).find("#main-form :input").each(function(x) {
if (x == 0) ids.push(parseInt($(this).val()));
if (x == 1) array.push($(this).val()));
});
}
});
}, i * 333);
}
解决方案
GET
您可以使用 Promises 以特定顺序执行请求。这是一个例子:
id = GM_getValue('id');
function makeGetRequest(url) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: url,
onload: function(response) {
resolve(response.responseText);
},
onerror: function(error) {
reject(error);
}
});
});
}
for (let i = 0; i < id.length; i++) {
console.log("Updating " + (i + 1) + " Title");
try {
const response = await makeGetRequest("***" + id[i] + "/***");
$(response).find("#main-form :input").each(function(x) {
if (x == 0) ids.push(parseInt($(this).val()));
if (x == 1) array.push($(this).val());
});
} catch (error) { // in case the GET request fails
console.error("Request failed with error code", error.status, ". Message is ", error.responseText);
}
}
在这个例子中,我创建了一个makeGetRequest()
返回 promise 的函数,它在 GET 成功时被解析,但在失败时被拒绝。
await
在继续之前等待 Promise 解决,并且try
存在捕获 Promise 拒绝(如果 GET 失败)。
参考:
推荐阅读
- postgresql - 如何在 PostgreSQL 中通过 varchar 选择带有 case-when 开关的整理顺序进行排序
- c# - 无法选中 ASP.NET Core MVC 视图中的复选框
- reactjs - 将 React 组件实现为 html 字符串
- c# - 为什么我无法使用驱动程序连接字符串连接到 MySql .Net,因为它与 Delphi 的 TADOQuery 一起使用?
- python - python3:timedrotatingfilehandler 日志轮换问题与具有多个脚本的相同日志文件
- javascript - Vue 多个组件和访问 Vuex 属性
- qt - 在 QWidget 内部,如果我试图同时调整小部件的大小,则 Qwt 绘图应该调整大小。如何将 resizeevent 应用于 QWidget
- powershell - 如何比较数据集与 adcomputer 记录?
- node.js - 如何从我的应用程序而不是 CLI 运行 Vault?
- c# - C# LanguageExt - 将多个异步调用组合成一个分组调用