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

新手上路,请多包涵

我在 api.js 中有一个 API 调用:

  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() ,我会看到完全返回的数据。

原文由 TWLATL 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 457
2 个回答

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

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

如果您的平台支持它,您还可以查看 异步/等待,这将使代码更接近您的原始代码

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

// can use steps here

原文由 Jamiec 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

 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
}

然后记住这个函数返回一个承诺,你需要等待它得到结果,例如在反应组件中:

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

当 promise 被 resolve 时,组件将更新,然后你可以使用数据(你需要在 render 方法中处理未定义的数据状态)

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

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

原文由 Dyo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题