【问题标题】:Reactjs: make a function to promise with axios in itReactjs:用 axios 做一个函数来承诺
【发布时间】:2021-02-09 18:07:36
【问题描述】:

我的 context provider 中有这个函数,我希望它返回一个承诺,以便我可以从 axios 访问返回的数据/p>

    const sendRquest =(service,data,method,url)=>{
        let base = api.find(item => item.name ===service )
        let config = {
            method: method,
            url: `${base.url}/${url}`,
            headers: {
              'x-clientId': clientId,
              'Content-Type': 'application/json',
            },
            data: data
          };
          axios(config)
          .then(function (res) {
            return res
          })
          .catch(function (error) {
            return error
          });
    }

我正在寻找的结果是在需要时在每个其他组件中编写这样的代码

sendRquest('usermanagement',data,'post','foo/bar').then(res=>console.log(res.data)).catch(err=>console.log(err))

【问题讨论】:

标签: javascript angularjs reactjs web axios


【解决方案1】:

你必须兑现承诺。

类似

    const sendRquest =(service,data,method,url)=>{
        let base = api.find(item => item.name ===service )
        let config = {
            method: method,
            url: `${base.url}/${url}`,
            headers: {
              'x-clientId': clientId,
              'Content-Type': 'application/json',
            },
            data: data
          };
        return axios(config)
          .then(function (res) {
            return res
          })
          .catch(function (error) {
            return error
          });
    }

请小心,因为您会像这样使用.catch 来“吞下”错误。 sendRquest 返回的承诺永远不会“失败”(拒绝),但会成功(解决)数据或错误负载。

【讨论】:

    【解决方案2】:

    完整的答案是这样的
    可以帮到大家

     const sendRquest =(service,data,method,url)=>{
            let base = api.find(item => item.name ===service )
            let config = {
                method: method,
                url: `${base.url}/${url}`,
                headers: {
                  'x-clientId': clientId,
                  'Content-Type': 'application/json',
                  'Authorization': token
                },
                data: data
              };
            return axios(config)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-11
      • 2020-03-24
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多