簡體   English   中英

React.js 如何順序調用 Axios?

[英]React.js How to call Axios sequentially?

  useEffect(() => {
    new Promise(resolve => {
      setTimeout(() => {
        resolve();
        /* 신규 로트번호 생성을 위한 다음 auto_increment 가져오기 */
        axios
          .get("http://localhost:8080/api/item/autoId")
          .then(response => {
            var output = response && response.data;
            const newLote = lote;
            newLote.lote = nowDate + "-" + output;
            setLote(newLote);
          })
          .catch(response => {
            console.log(response);
          });
      }, 600);
    }),
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          //재고조회 (로트번호 검색기능)
          axios
            .get("http://localhost:8080/api/item/1")
            .then(response => {
              var output = response && response.data;

              const newLookup = Object.assign({}, lookup);

              for (var i = 0; i < output.list.length; i++) {
                var value = output.list[i].lote_id;
                newLookup.lookup[value] = value;
              }

              newLookup.lookup[lote.lote] = lote.lote;
              setLookup(newLookup);
              console.log(lookup.lookup);

              const newState = Object.assign({}, state);
              newState.columns[1].lookup = lookup.lookup;
              setState(newState);
            })
            .catch(response => {
              console.log(response);
            });
        }, 600);
      }),
      new Promise(resolve => {
        setTimeout(() => {
          resolve();
          /* 출고 이력 불러오기 */
          axios
            .get("http://localhost:8080/api/shipping/history/1")
            .then(response => {
              var output = response && response.data;

              const newState = Object.assign({}, state);
              newState.data = output.list;
              setState(newState);
            })
            .catch(response => {
              console.log(response);
            });
        }, 600);
      });
  }, []);

我的函數組件中的 useEffect() 函數如下所示。

下面一共是三個異步通信。

問題是這些異步通信每次都不會經過相同的順序。

如代碼所示,您如何進行異步通信?

我相信您正在尋找的是Promise chaining 您可以使用 Promise.all(),或者簡單地這樣做。 下面的例子是一種使用承諾鏈的方法。 您可以通過 Google Promise chaining了解更多信息 :)

axios.get('1st api call').then(res1 => {
    //some code related to 1st
    return axios.get('2nd api call')
}).then(res2 => {
    //some other code related to 2nd
    return axios.get('3rd api call')
}).then(res3 => {
    //some other code related to 3rd
})

您可以刪除那些看似錯位的setTimeoutsnew Promise ,然后嘗試這樣的操作。 上面代碼的作用是,在第一個API調用成功后,調用第二個,當第二個調用成功時,調用第三個API調用。

希望我說的是你的問題,這會有所幫助!

如果您希望輸出嚴格排序為輸入,您可以使用p-queue ,具有並發控制的 Promise 隊列。

  useEffect(() => {
    const myPromises = [
      () =>
        new Promise(resolve =>
          setTimeout(() => {
            resolve();
            console.log("First(slow)");
          }, 5000)
        ),
      () =>
        new Promise(resolve =>
          setTimeout(() => {
            resolve();
            console.log("Second(fast)");
          }, 100)
        ),
      () =>
        new Promise(resolve =>
          setTimeout(() => {
            resolve();
            console.log("Third(slower)");
          }, 10000)
        )
    ];

    queue.addAll(myPromises);
  }, [queue]);

沙盒

更新你的代碼應該是這樣的

  useEffect(() => {
    const myPromises = [
      () =>
        axios
          .get("http://localhost:8080/api/item/autoId")
          .then(x => console.log(x)),

      () =>
        axios
          .get("http://localhost:8080/api/item/1")
          .then(x => console.log(x)),

      () =>
        axios
          .get("http://localhost:8080/api/shipping/history/1")
          .then(x => console.log(x))
    ];

    queue.addAll(myPromises);
  }, [queue]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM