【问题标题】:Return Promise from Axios?从 Axios 返回 Promise?
【发布时间】:2016-12-27 00:24:44
【问题描述】:

我想知道如何从 Axios 返回一个承诺?我不确定是否需要使用拦截器?

我现在有这个代码

export function fetchStorage() {
    return function (dispatch) {
      return new Promise(function(resolve, reject) {
        if (1 === 1) {
          resolve('it works!');
        } else {
          reject(':(');
        }
      });
    };
}

this.props.fetchStorage().then(function() {
           console.log('then');
        });

现在说我想更改 fetchStorage 以通过 ajax 做某事,我会喜欢它

 var instance = axios.create({
            baseURL: 'http://localhost:54690/api',
            timeout: 2000,

        });

        instance.get('/Storage/Get')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });

我如何返回承诺而不是在这里执行?

编辑

只是为了澄清我为什么这样做,我有这样的事情

  componentWillMount() {
        this.props.setPreLoader(true);
        this.props.fetchStorage().then(function() {
           this.props.setPreLoader(false);
        });
    }

export function fetchStorage() {
    return function (dispatch) {
        return new Promise(function (resolve, reject) {
            axiosInstant.get('/Storage/Get')
                .then(function (response) {
                    let payload = response.data;
                    console.log(payload);
                    dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    };
}

【问题讨论】:

  • 为什么不return instance.get('/Storage/Get') 我在这里错过了什么?
  • 好吧,我使用的是 redux 模式,所以我需要发送调度,如果我像你一样返回,那么我每次使用该函数时都必须记住发送调度。跨度>
  • @chobo2 我不明白你为什么不返回 axios 已经给你的承诺。
  • 我的编辑现在基于 JokerManh 的回答。我希望我不需要用那个承诺来包装它,但我现在不确定如何在之后返回承诺。我的 CompnentWillMount 代码看起来是我想要实现的。
  • 你的fetchStorage 函数没有返回一个promise 它返回一个函数,该函数在调用时会返回一个promise。所以你不能将then 链接到它。

标签: javascript promise axios


【解决方案1】:

Axios 是基于 Promise 的,所以你不需要将它包装在 Promise 中, 你可以做这样的事情,和 axiosInstance.[post|put|get| end etc.] 方法将返回 promise。

export function fetchStorage() {
    return function (dispatch) {
       return axiosInstant.get('/Storage/Get')
                .then(function (response) {
                    let payload = response.data;
                    console.log(payload);
                    dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
                })
                .catch(function (error) {
                    console.log(error);
                });
    };
}

【讨论】:

    【解决方案2】:

    一定有更好的方法,但你可以

    export async function fetchStorage() {
        return async function (dispatch) {
            try {
                const { data } = await axiosInstant.get('/Storage/Get')
                dispatch({ type: actions.FETCH_STORAGE, payload: { storages: data } })
                return data
            } catch (e) {
                console.error(e)
            }
        }
    }
    

    那你得按如下方式使用fetchStorage

    this.props.fetchStorage().then(async function(response) {
        let payload = await response()
    });
    

    【讨论】:

      【解决方案3】:

      查看示例:

       return new Promise(function (resolve, reject) {
          var instance = axios.create({
              baseURL: 'http://localhost:54690/api',
              timeout: 2000,
          });
          instance.get('/Storage/Get')
              .then(function (response) {
                  if(1 === 1)
                  resolve(response);
              })
              .catch(function (error) {
                  reject(error);
              });
      
       });
      

      【讨论】:

      • 啊,我想也许它有自己的回报,我不需要包装它。
      • @chobo2 看起来确实像是返回了一个承诺。或者,至少是一个thennable。
      猜你喜欢
      • 2017-09-13
      • 2019-05-08
      • 1970-01-01
      • 2019-02-13
      • 2021-07-23
      • 2022-01-01
      • 1970-01-01
      • 2019-08-07
      • 2021-10-26
      相关资源
      最近更新 更多