14

Axios から Promise を返すにはどうすればよいですか? インターセプターを使用する必要があるかどうかわかりません。

私は今このコードを持っています

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);
                });
        });
    };
}
4

3 に答える 3

-6

サンプルを参照してください:

 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);
        });

 });
于 2016-08-19T18:56:03.300 に答える