0

I am calling one API.in the then section of API call, i am calling another API. the output of first API will be passed to another API.

await axios
  .post(process.env + '/certificates/upload', {
      "name": "Shruti"
    }
  })
.then((response: any) => {
      filenames = JSON.stringify(response.data.office);

      axios // Not able to write async here
        .patch(process.env + "/certificates/", {
          file: filenames
        })
        .then(function(response: any) {
          alert(' Record updated successfully');
        })
        .catch((err: any) => {
          alert('Error in updating the record');
        });

I am not able to use await in second API call. Where should I put async to use await in second API call? first call is working properly. also Is there any better way to call consecutive API and Passing output of first call to second.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Shruti sharma
  • 199
  • 6
  • 21
  • 67
  • 2
    you dont need to use .then when using await instead you can write something similar too let response = await axios .post(process.env+ '/certificates/upload',{"name":"Shruti"} }) let filenames = JSON.stringify(response.data.office); let response = await axios.patch(process.env+"/certificates/", { file: filenames }) – R Nair Feb 18 '22 at 06:26
  • 1
    Relevant: [Aren't promises just callbacks?](https://stackoverflow.com/q/22539815) – VLAZ Feb 18 '22 at 06:31
  • so even if I dont use await in second call it will always work? – Shruti sharma Feb 18 '22 at 06:53

1 Answers1

1

Find the function that contains the statement you wish to await. Add async to the beginning of that function.

More generally, avoid mixing async/await with chained .then/.catch.

I think this is what you want:

try {
    let response1 = await axios.post(
        process.env + '/certificates/upload',
        { name: "Shruti" }
    )
    let filenames = JSON.stringify(response1.data.office)

    await axios.patch(
        process.env + "/certificates/",
        { file: filenames }
    )

    alert(`Update succeeded`)

} catch( error ) {
    alert(`Update failed`)
}
Tom
  • 8,509
  • 7
  • 49
  • 78