简体   繁体   English

如何链接 axios HTTP 请求

[英]How to chain axios HTTP requests

I have 2 async await functions - one of them makes axios post request and another one - axios get request.我有 2 个异步等待函数 - 其中一个发出 axios post 请求,另一个 - axios get 请求。

How could I chain them so that I would wait until the post operation is done and after it is completed, fetch new and updated objects?我如何将它们链接起来,以便我等到 post 操作完成并完成后,获取新的和更新的对象?

const expensesListToDB = async () => {
    await axios.post('http://localhost:4000/app/expenseslist', 
    {
        expenseTitle: Expense,
        expenseAmount: Amount
    });
}

const expensesListFromDB = async () => {
    await axios.get('http://localhost:4000/app/expenseslist')
    .then(
    response => setExpenseAndAmountList(response.data && response.data.length > 0 ? response.data : []));
}

expensesListToDB();
expensesListFromDB();

Thanks!谢谢!

you can put expensesListFromDB() in the 'then' method of the Axios.您可以将费用列表从数据库()放在 Axios 的“then”方法中。

const expensesListToDB = async () => {
    await axios.post('http://localhost:4000/app/expenseslist', 
    {
        expenseTitle: Expense,
        expenseAmount: Amount
    }).then(
    response => expensesListFromDB()); }

const expensesListFromDB = async () => {
    await axios.get('http://localhost:4000/app/expenseslist')
    .then(
    response => setExpenseAndAmountList(response.data && response.data.length > 0 ? response.data : [])); }

expensesListToDB();

I suppose the API is in your control, the answers given by others are viable i would imagine a system where you return the new document in the response of the post request and just use it from their making it one single request我想 API 在你的控制之下,其他人给出的答案是可行的

To have error handling and fault tolerance you could design your API response like this要进行错误处理和容错,您可以像这样设计 API 响应

{ "statusCode":"200",
  "event":"doc_added_successfully",
  "newDocs":{
  }

You can return Promise from expensesListToDB and in the .then block you can run the function expensesListFromDB您可以从expensesListToDB .then返回Promise ,在.then块中您可以运行功能expensesListFromDB .then从数据库

Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.一旦发出 HTTP POST 请求,Axios 将返回一个已完成或拒绝的承诺,具体取决于后端服务的响应。

const expensesListToDB = () => {
  return axios.post("http://localhost:4000/app/expenseslist", {
    expenseTitle: Expense,
    expenseAmount: Amount,
  });
};

const expensesListFromDB = async () => {
  await axios
    .get("http://localhost:4000/app/expenseslist")
    .then((response) =>
      setExpenseAndAmountList(
        response.data && response.data.length > 0 ? response.data : []
      )
    );
};

expensesListToDB().then((data) => {
  expensesListFromDB();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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