0
function SendObj(id, language) {
    setObjSending(true);
    Promise.all(
      objBoxes.map((box) => {
        return axios
          .post('/panel/subtask/paint-object/', {
            language: language,
            details: 'paint object',
            sub_task_paint: id,
            sub_task_color: [box.colorId],
            image_name: box.image_name,
          })
          .catch(() => setObjSending(false));
      })
    )
      .then(() => {
        message.success('subtask saved!');
        history.goBack();
      });
  }

The above function makes the produced Ids in database to be not in order of box indexes. Is there a way to do the axios call sequentially to fix this?

FZs
  • 16,581
  • 13
  • 41
  • 50
MinaFa
  • 259
  • 2
  • 13
  • You [shouldn't and can't](https://stackoverflow.com/q/14220321/8376184) make it *synchronous*, what you want is to make them *sequential*... – FZs Dec 23 '20 at 07:47
  • Does this answer your question? [wait for one fetch to finish before starting the next](https://stackoverflow.com/questions/58492609/wait-for-one-fetch-to-finish-before-starting-the-next) (It uses `fetch` instead of `axios`, but it's quite the same) – FZs Dec 23 '20 at 07:49

1 Answers1

2

Iterate the objBoxes using for and await for each axios request.

async function SendObj(id, language) {
  setObjSending(true);
  for (let i = 0; i < objBoxes.length; i++) {
    await axios
      .post('/panel/subtask/paint-object/', {
        language: language,
        details: 'paint object',
        sub_task_paint: id,
        sub_task_color: [objBoxes[i].colorId],
        image_name: objBoxes[i].image_name,
      })
      .catch(() => setObjSending(false));
  }
  message.success('subtask saved!');
  history.goBack();
}
wangdev87
  • 8,611
  • 3
  • 8
  • 31