queue.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. function Queue() {
  2. let waitingQueue = this.waitingQueue = [];
  3. let isRunning = this.isRunning = false; // 记录是否有未完成的任务
  4. function execute(task, resolve, reject) {
  5. task()
  6. .then((data) => {
  7. resolve(data);
  8. })
  9. .catch((e) => {
  10. reject(e);
  11. })
  12. .finally(() => {
  13. // 等待任务队列中如果有任务,则触发它;否则设置isRunning = false,表示无任务状态
  14. if (waitingQueue.length) {
  15. const next = waitingQueue.shift();
  16. execute(next.task, next.resolve, next.reject);
  17. } else {
  18. isRunning = false;
  19. }
  20. });
  21. }
  22. this.exec = function(task) {
  23. return new Promise((resolve, reject) => {
  24. if (isRunning) {
  25. waitingQueue.push({
  26. task,
  27. resolve,
  28. reject
  29. });
  30. } else {
  31. isRunning = true;
  32. execute(task, resolve, reject);
  33. }
  34. });
  35. }
  36. }
  37. /* 队列实例,某些平台一起使用多个组件时需要通过队列逐一绘制,否则部分绘制方法异常,nvue端的iOS gcanvas尤其明显,在不通过队列绘制时会出现图片丢失的情况 */
  38. export const queueDraw = new Queue();
  39. export const queueLoadImage = new Queue();