如何使用 async GM_xmlhttpRequest 按原始顺序返回值?

时间:2021-01-02 20:43:21

标签: javascript jquery tampermonkey userscripts

我正在尝试制作一个 Tampermonkey 脚本来更新某个站点上的日期。 我从一个站点获得了一个 id 数组,我正在使用该数组的 id 从中请求数据。之后,我必须返回每个Input的数据。

由于函数是async,它以随机顺序返回数据,但我需要这些新数组以原始顺序返回。我尝试过同步和 Promise,但第一个太慢,我不明白第二个。

我可以对 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);
}

1 个答案:

答案 0 :(得分:0)

您可以使用 Promise 以特定顺序执行 GET 请求。举个例子:

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 成功时为 resolved,但在失败时为 rejected

await 在继续之前等待 Promise 解决,并且 try 存在以捕获 Promise 拒绝(如果 GET 失败)。

参考文献: