【发布时间】: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