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

时间:2018-02-13 13:15:28

标签: javascript reactjs es6-promise

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

类似的东西:

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

答案 2 :(得分:0)

您有2个选项可以转换所提取的数据:

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

    while ($row = mysql_fetch_array($resval))
{

//  $amount  = $row['amount'] == 0 ? '' : number_format($row['amount']);
    echo '<tr>
            <td name="getit">'.$row['id_raw'].'</td>
            <td>'.$row['prodname'].'</td>
            <td name="getit1">'.$row['kl'].'</td>
            <td>'.$row['ounce'].'</td>
            <td>'.$row['gram'].'</td>
            <td>'.$row['quantity'].'</td>
            <td>'.$row['price'].'</td>
            <td>'.$row['supplier'].'</td>
            <td>'.$row['dateclaim'].'</td>
            <td>'.$row['shelflife'].'</td>
            <td><input step="any" type=number name="aji" style="width:100%;"></td>
            <td><center><input type=submit value="UPDATE" class="button-save-update" name="button1"></center></td>
            </tr>';

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

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

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

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

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

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

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

要在我们的组件中获得与选项1相同的结果,我们将使用它:

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

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