【发布时间】:2021-03-16 21:21:03
【问题描述】:
我有一个承诺,其中包含另一个 API 调用者承诺,其中包含解析器。现在当我想使用 .then 作为父承诺时,我做不到,错误提示 Cannot read property 'then' of undefined,下面是我的示例代码
const getData = () => dispatch => new Promise((resolve) => {
return apiService
.getByParameter(abc)
.then((data) => {
dispatch(update({
name: data.name
}));
resolve();
})
.catch(() => {
});
});
现在每当我尝试这样做时
this.getData().then({
<--something-->
});
它抛出一个错误为Cannot read property 'then' of undefined
getByParamter 方法来自一个类,因为
getByParameter(...params) {
const endpoint = `${this.getEndpoint.call(this, ...params)}`;
const timeInitiated = performance.now();
return request(() => axios.get(endpoint, extraHeaders), timeInitiated,
endpoint, ACTIONS.ACTION_GET);
}
const request = (rest, timeInitiated, endpoint, action) =>
new Promise((resolve, reject) => {
rest().then(({ data }) => {
const timeResolved = performance.now();
const timeCalculated = millisToMinutesAndSeconds(timeResolved - timeInitiated);
if (endpoint !== LOGS_ENDPOINT && timeCalculated > MAX_EXECUTION_TIME) {
apiLogger.warn(`The endpoint ${endpoint} took ${timeCalculated} seconds for ${action}`);
}
resolve(data);
})
.catch((response) => {
if (!isCancel(response)) {
reject(response);
} else {
apiLogger.debug('Request cancelled');
}
});
});
请建议应该是什么解决方案来满足我的需要。
【问题讨论】:
-
当 Promise 已经存在时不要使用 Promise 构造函数 - 它被称为 stackoverflow.com/questions/23803743/…
-
getData()方法没有返回值。但是你的代码是一个反承诺模式。 -
@BenjaminGruenbaum 这是否意味着,链接承诺是我应该这样做的方式?
-
@RandyCasburn 我尝试将resolve放在最后,但那部分代码无法访问......
-
但是 Redux-Thunk 不会遵循反模式吗?因为最初我的 getData 方法是一个带有调度程序的操作......更新我的代码以获得更广泛的图片
标签: javascript ecmascript-6 es6-promise redux-thunk