Promise 实现队列打印

263 阅读1分钟

需求

接到产品需求,需要有两个Modal弹框,彼此存在顺序关系,而没有业务逻辑关系,后一个弹框点击确定后将向后端单次循环调用接口

方案确定

弹框顺序考虑用将第二个弹框作为第一个弹框的then方法返回的promise对象,单次循环调用可以通过将创建一个Promise对象,然后不断创建该对象的then方法中请求后端接口。

代码实现

弹框

const p1 = () =>
      new Promise((resolve, reject) => {
        Modal.confirm({
          title: <div> titile</div>,
          content: (
            <div>弹框1</div>
          ),
          okText: 'confirm',
          cancelText: 'cancel',
          onOk: () => {
            console.log('ok');
            resolve();
          },
          onCancel: () => {
            console.log('cancel');
            reject();
          },
        });
      });
const p2 = () =>
      new Promise((resolve) => {
        Modal.confirm({
          title: <div> titile</div>,
          content: <div>弹框2</div>,
          okText: 'confirm',
          cancelText: 'cancel',
          onOk: () => {
            fetch();
            resolve();
          },
          onCancel: () => {
            console.log('cancel');
            resolve();
          },
        });
      });
p1().then(() => p2());

循环方法

const fetch = () => {
    function queue(things: any) {
      let promise = Promise.resolve();
      things.forEach((element: any) => {
        promise = promise.then(() => {
          return new Promise((resolve) => {
            ajax(element, resolve);
          });
        });
      });
    }
    queue(['h1', 'h2', 'h3']);
  };

  const ajax = (id: any, callback: any) => {
    setTimeout(() => {
      console.log(id);
      callback();
    }, 1000);
  };