gpt4 book ai didi

javascript - 从 .then() 接收 Promise {}

转载 作者:行者123 更新时间:2023-11-30 11:23:52 25 4
gpt4 key购买 nike

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

最佳答案

您需要等到您的异步调用被解决。您可以通过链接另一个 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

关于javascript - 从 .then() 接收 Promise {<pending>},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com