使用Promise解决请求先后次序问题

108 阅读2分钟

Situation

需求:点击事件实现快速新增一篇文章

在这里插入图片描述
最开始的方案是根据文章uid去查找model中存的list数据,再发送一个新增请求即可实现。
但是list中没有存文章的content,此时就不得不发送两次请求,先获取文章详情,拿到详情内容再作为参数发送新增请求。

问题:详情请求数据成功之后,再请求新增接口。也就是说第二次的请求需要使用第一次请求得到的数据。

Action

涉及到一个异步操作,必须第一个请求发送且成功的情况下,才发送第二次请求。
思路:使用promise实现异步操作。
需要将resolve和reject一并传入model。

 // 快速新增
  handleFastAddArticle = (record) => {
    const { uid = '' } = record;
    const { dispatch, GeneralManagementModel: { DEFAULT_PAGINATION } } = this.props;
    //new一个promise对象
    new Promise((resolve, reject) => {
      dispatch({
        type: 'GeneralManagementModel/getAsyncArticleDetail',
        payload: {
          resolve,
          reject,
          uid,
        }
      })
    }).then(() => {
      confirm({
        title: '是否快速增加该文章',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'GeneralManagementModel/addArticle',
            payload: { DEFAULT_PAGINATION }
          })
        }
      });
    }).catch(() => {

    })
  }

model函数部分

//异步请求数据
 *getAsyncArticleDetail({ payload }, { put, call, select }) {
      const { resolve, reject } = payload; //接收index传入的resolve和reject
      const moduleType = yield select((state) => state.GeneralManagementModel.moduleType);
      let response = {};
      switch (moduleType) {
        case MODULETYPE.EXPOSURE_MANAGEMEN.key:
          response = yield call(GenManageService.getExposureDetail, payload);
          break;
        case MODULETYPE.POLICY_NORMS.key:
          response = yield call(GenManageService.getPolicyDetail, payload);
          break;
        case MODULETYPE.CONSUMPTION_WARNING.key:
          response = yield call(GenManageService.getCautionDetail, payload);
          break;
        default:
          break;
      }
      const { code, data } = response;
      if (Number(code) !== 0) {
        message.error('获取文章详情失败');
        reject();
        return;
      }
      //调用resolve方法,参数为获取到的详情data,也可以不传参,直接返回一个promise对象
      resolve(data);
      yield put({
        type: 'save',
        payload: {
          articleDetail: data,
        },
      })
    },

Result

现在就可以了,点击先获取到文章详情,再将已经获取到的数据经过处理当成参数发送新增文章请求。
至此,就实现快速新增功能了。

Promise 对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成,又称 Fulfilled)和 Rejected(已失败)。

通过回调里的resolve(data)将这个promise标记为resolverd,然后进行下一步then((data)=>{//do something}),resolve里的参数就是我们要传入then的数据。