从 .then() 接收 Promise {<pending>}

IT技术 javascript reactjs es6-promise
2021-04-28 19:10:58

我有一个 API 调用api.js

 export const getGraphData = (domain, userId, testId) => {
   return axios({
     url: `${domain}/api/${c.embedConfig.apiVersion}/member/${userId}/utests/${testId}`,
     method: 'get',
   });
 };

我有一个 React 助手,可以获取该数据并对其进行转换。

import { getGraphData } from './api';

const dataObj = (domain, userId, testId) => {

  const steps = getGraphData(domain, userId, testId)
  .then((result) => {
    return result.attributes;
  });

  console.log(steps);

  // const steps = test.get('steps');
  const expr = /select/;

  // build array of steps that we have results in
  const resultsSteps = [];

  steps.forEach((step) => {
    // check for types that contain 'select', and add them to array
    if (expr.test(step.get('type'))) {
      resultsSteps.push(step);
    }
  });

  const newResultsSteps = [];

  resultsSteps.forEach((item, i) => {
    const newMapStep = new Map();
    const itemDescription = item.get('description');
    const itemId = item.get('id');
    const itemOptions = item.get('options');
    const itemAnswers = item.get('userAnswers');
    const newOptArray = [];
    itemOptions.forEach((element) => {
      const optionsMap = new Map();
      let elemName = element.get('value');
      if (!element.get('value')) { elemName = element.get('caption'); }
      const elemPosition = element.get('position');
      const elemCount = element.get('count');

      optionsMap.name = elemName;
      optionsMap.position = elemPosition;
      optionsMap.value = elemCount;
      newOptArray.push(optionsMap);
    });
    newMapStep.chartType = 'horizontalBar';
    newMapStep.description = itemDescription;
    newMapStep.featured = 'false';
    newMapStep.detailUrl = '';
    newMapStep.featuredStepIndex = i + 1;
    newMapStep.id = itemId;
    newMapStep.isValid = 'false';
    newMapStep.type = 'results';
    const listForNewOptArray = List(newOptArray);
    newMapStep.data = listForNewOptArray;
    newMapStep.userAnswers = itemAnswers;
    newResultsSteps.push(newMapStep);
  });

  return newResultsSteps;
};

export default dataObj;

问题是steps,当在外部登录时.then()返回一个Promise {<pending>}. 如果我登录results.attributes.then(),我会看到数据完全返回。

3个回答

您需要等到异步调用得到解决。您可以通过链接另一个来做到这一点then

getGraphData(domain, userId, testId)
  .then((result) => {
    return result.attributes;
  })
  .then(steps => {
     // put the rest of your method here
  });

如果您的平台支持它,您还可以查看async/await,这将允许代码更接近您的原始代码

const steps = await getGraphData(domain, userId, testId)
  .then((result) => {
    return result.attributes;
  });

// can use steps here

您有 2 个选项来转换获取的数据:

第一个选项:创建一个异步函数,返回一个带有修改数据的Promise:

const dataObj = (domain, userId, testId) => {
  return getGraphData(domain, userId, testId).then((result) => {
    const steps = result.attributes;
    const expr = /select/;
    // build array of steps that we have results in
    const resultsSteps = [];

    steps.forEach((step) => {
      // check for types that contain 'select', and add them to array
      if (expr.test(step.get('type'))) {
        resultsSteps.push(step);
      }
    });

    const newResultsSteps = [];

    resultsSteps.forEach((item, i) => {
      const newMapStep = new Map();
      const itemDescription = item.get('description');
      const itemId = item.get('id');
      const itemOptions = item.get('options');
      const itemAnswers = item.get('userAnswers');
      const newOptArray = [];
      itemOptions.forEach((element) => {
        const optionsMap = new Map();
        let elemName = element.get('value');
        if (!element.get('value')) {
          elemName = element.get('caption');
        }
        const elemPosition = element.get('position');
        const elemCount = element.get('count');

        optionsMap.name = elemName;
        optionsMap.position = elemPosition;
        optionsMap.value = elemCount;
        newOptArray.push(optionsMap);
      });
      newMapStep.chartType = 'horizontalBar';
      newMapStep.description = itemDescription;
      newMapStep.featured = 'false';
      newMapStep.detailUrl = '';
      newMapStep.featuredStepIndex = i + 1;
      newMapStep.id = itemId;
      newMapStep.isValid = 'false';
      newMapStep.type = 'results';
      const listForNewOptArray = List(newOptArray);
      newMapStep.data = listForNewOptArray;
      newMapStep.userAnswers = itemAnswers;
      newResultsSteps.push(newMapStep);
    });
    return newResultsSteps;
  });
};

使用 es7 async/await 语法应该是:

const dataObj = async (domain, userId, testId) => {
    const result = await getGraphData(domain, userId, testId);
    const steps = result.attributes;
    ... modify the data
}

然后请记住,此函数返回一个Promise,您需要等待它获得结果,例如在react组件中:

componentDidMount(){
   dataObj('mydomain', 'myuserId', 'mytestId').then((res) => {
       this.setState({ data: res });
   }
}

当Promise被解析时,组件将更新,然后您可以使用数据(您需要在渲染方法中处理未定义的数据状态)

第二个选项:创建一个同步功能来修改数据:

const dataObj = (steps) => {
    const expr = /select/;
    const resultsSteps = [];

    steps.forEach((step) => {
    ...
    }
    return newResultsSteps;
};

为了在我们的组件中获得与选项 1 相同的结果,我们将像这样使用它:

componentDidMount(){
   getGraphData('mydomain', 'myuserId', 'mytestId').then((res) => {
       const modifiedData = dataObj(res);
       this.setState({ data: modifiedData });
   }
}

这就是Promise的工作方式。当您尝试使用数据时,数据尚未准备好,因此您应该将所有处理移至.then. 你的变量是 a 的原因Promise {<pending>}是因为你可以将其他东西链接到它上面。

就像是:

steps.then((steps) => {
    ...
});