2016-08-19 109 views
8

我想知道我该如何退还承诺表格Axios?我不确定是否需要使用拦截器?回归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); 
       }); 
     }); 
    }; 
} 
+1

为什么不'回instance.get('/存储/得到')'我在这里错过了什么? –

+0

以及我正在使用redux模式,所以我需要发送调度,如果我只是像你一样返回,那么我总是必须记得每次使用该函数时发送该调度。 – chobo2

+0

@ chobo2我不明白你为什么没有回复axios已经给你的承诺。 –

回答

-5

见样本:

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

}); 
+1

啊,以为也许它有自己的回报承诺,我不需要包装它。 – chobo2

+0

@ chobo2当然看起来像是回报了一个承诺。或者,至少是一个可以接受的。 –