【问题标题】:ES6: Resolving Promise containing other Promise so that parent can use .thenES6:解析包含其他 Promise 的 Promise,以便父级可以使用 .then
【发布时间】: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


【解决方案1】:

你的箭头函数立即,无条件地返回另一个函数,而不是一个承诺!

const getData = () => (dispatch => new Promise(...))

getData() 是一个函数,所以.then 上不存在。

自己试试

console.assert(typeof getData() !== "function", "`.then` doesn't exist on a function");

老实说,这段代码应该移除 dispatch 回调并让被调用者使用 .then 处理程序,这就是 promise 的用途。

const getData = async () => {
    const data = await apiService.getByParameter(abc);

    return update(data);
});

【讨论】:

  • 更新了我的代码以获得 getByParamter 中的内容
  • @Noob 好吧现在我们需要知道request 是否返回一个promise。您必须遵循整个控制流链来确定是否返回了 Promise。
  • 是的,then on () => axios.get(endpoint, extraHeaders) 在里面,有问题更新
  • 在意识到 Stuck 所说的之后更新。
【解决方案2】:

getData 返回一个需要调度参数的函数。如果您调用该函数,那么您将得到一个承诺。

const dispatch = useDispatch();
const myPromise = this.getData()(dispatch);

注意最后一行中的空括号,后面跟着以 dispatch 作为参数的调用 ()(dispatch)

换句话说,getData 创建了一个 thunk,您可以使用它来创建 Promise。

const thunkFunction = getData();
const myPromise = thunkFunction(dispatch);
myPromise.then(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多