Async_Requests

异步Requests库

目前为 2021-08-26 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/431423/964206/Async_Requests.js

  1. // ==UserScript==
  2. // @name Async_Requests
  3. // @namespace https://blog.chrxw.com
  4. // @version 1.1
  5. // @description 异步Requests库
  6. // @author Chr_
  7. // ==/UserScript==
  8.  
  9. //==============================================================
  10. class Request {
  11. constructor(timeout = 3000) {
  12. this.timeout = timeout;
  13. }
  14. get(url, opt = {}) {
  15. return this.baseRequest(url, 'GET', opt, 'json');
  16. }
  17. getHtml(url, opt = {}) {
  18. return this.baseRequest(url, 'GET', opt, '');
  19. }
  20. getText(url, opt = {}) {
  21. return this.baseRequest(url, 'GET', opt, 'text');
  22. }
  23. post(url, data, opt = {}) {
  24. opt.data = JSON.stringify(data);
  25. return this.baseRequest(url, 'POST', opt, 'json');
  26. }
  27. baseRequest(url, method = 'GET', opt = {}, responseType = 'json') {
  28. Object.assign(opt, {
  29. url, method, responseType, timeout: this.timeout
  30. });
  31. return new Promise((resolve, reject) => {
  32. opt.ontimeout = opt.onerror = reject;
  33. opt.onload = ({ readyState, status, response, responseText }) => {
  34. if (readyState === 4 && status === 200) {
  35. if (responseType == 'json') {
  36. resolve(response);
  37. } else if (responseType == 'text') {
  38. resolve(responseText);
  39. }
  40. } else {
  41. console.error('网络错误');
  42. console.log(readyState);
  43. console.log(status);
  44. console.log(response);
  45. reject('解析出错');
  46. }
  47. }
  48. GM_xmlhttpRequest(opt);
  49. });
  50. }
  51. }
  52. const $http = new Request();