WsM.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { TipsLayer } from "../../prefab/layer/TipsLayer";
  2. import { Tips } from "../mgr/Tips";
  3. import { WS, WsRequest, WsResponse } from "../net/WS";
  4. export default class WsM {
  5. private static _ins: WsM;
  6. public static get ins(): WsM {
  7. return (WsM._ins ??= new WsM());
  8. }
  9. public async syncRequest(
  10. protocolId: number,
  11. data: any,
  12. timeout: number = 8000
  13. ): Promise<any> {
  14. return new Promise((resolve, reject) => {
  15. let getData = false;
  16. let cb = (msg: WsResponse) => {
  17. getData = true;
  18. console.log("websocket msg", msg);
  19. WS.ins.off(protocolId, cb, cb);
  20. if (msg.success == true) {
  21. if (msg.data) {
  22. resolve(msg.data);
  23. } else {
  24. resolve({});
  25. }
  26. } else {
  27. console.error(msg);
  28. Tips.show(msg.msg);
  29. resolve(null);
  30. }
  31. };
  32. WS.ins.on(protocolId, cb, cb);
  33. WsRequest.create(protocolId).setData(data).send();
  34. setTimeout(() => {
  35. // WS.ins.off(protocolId, cb, cb);
  36. // reject("timeout");
  37. if (getData) {
  38. return;
  39. }
  40. WS.ins.reconnect();
  41. TipsLayer.show({
  42. title: "Hello",
  43. singleName: "timeout",
  44. content: "Welcome back!",
  45. forceConfirm: true,
  46. link: null,
  47. onConfirm: () => {
  48. // resolve(null);
  49. },
  50. });
  51. }, timeout);
  52. });
  53. }
  54. }