1. 程式人生 > >mobx內建流flow非同步請求

mobx內建流flow非同步請求

什麼是flow

  • 它與async / await的工作方式相同。 只需使用函式*而不是async和yield而不是await。

  • flow的優點在於他在預發上非常接近async / await,並且非同步部分不需要手動操作包裝,從而產生非常乾淨的程式碼。

  • flow只能用作函式而不能用作裝飾器。

應用

import axios from "axios";

export function getSearchData(keyword, moduleType, start = 0, count = 6) {
// 底層請求使用 axios: 基於promise 的HTTP 庫,可以用在瀏覽器和node.js中。
return axios.get(`/${moduleType}/search`, { params: { q: keyword, start, count } }); }
// 匯入getSearchData方法
import { getSearchData } from '../../../apis';
fetchSearchData = flow(
  function*(keyword, module, start, count) {
    try {
      const response = yield getSearchData(keyword, module.value, start, count);
      const
data = response.data[module.field]; this.setSearchData(data); } catch (error) { console.log(error); } }.bind(this) ); // 呼叫fetchSearchData方法 this.fetchSearchData(value, currentModule);