简体   繁体   中英

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);
      });
  }, []);

The useEffect () function in my function components is shown below.

Below is a total of three asynchronous communication.

The problem is that those asynchronous communications don't go through the same order each time.

How do you proceed with asynchronous communication as shown in the code?

I believe what you are looking for is Promise chaining . You can use Promise.all(), or simply do it like this. The following example is a way to use promise chaining. You can Google Promise chaining to learn more about it :)

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
})

You can remove those seemingly misplaced setTimeouts and new Promise , and try something like this. What the above code is doing is, After the 1st API call is a success, the 2nd one is called, and when the 2nd one is a success, the 3rd API call is called.

Hope what I'm talking about is your problem, and this helps!

If you want the outputs strictly ordered as the inputs, You can use p-queue , Promise queue with concurrency control.

  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]);

sandbox

Update your code should be something like this

  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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM