0

I have the following function that gets a survey from Qualtrics:

const fetchQualtricsSurvey = async () => {
    const token = await getAccessToken();
    const progress = await startResponseExport(token);
    const fileId = await getResponseExportProgress(token, progress);
    const survey = await getResponseExportFile(token, fileId);
    console.log(survey);
};

fetchQualtricsSurvey();

It's currently logging the survey to the console. However, I want to use the JSON that I get in other parts (e.g., visualizing the data using other libraries).

Everytime I try to create a global variable that holds survey I get a promise pending.

Here is the getResponseExportFile function for reference:

async function getResponseExportFile(accessToken, fileId) {
    try {
        const res = await axios(
            `${baseUrl}/API/v3/surveys/${surveyId}/export-responses/${fileId}/file`,
            {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            }
        );
        return res.data.responses;
    } catch (err) {
        console.log(err);
    }
}

How on earth do I use survey outside of this whole async function? Is it even possible? I need to access properties of survey object and use them as values somewhere else.

SevenSouls
  • 539
  • 3
  • 12
  • 1
    First, add a return statement at the end of `fetchQualtricsSurvey`, eg `return survey`. As an async function, fetchQualtricSurvey will be returning a promise, so to interact with the value inside the promise you'll `await` it, as in `const survey = await fetchQualtricsSurvey(); //do something with survey on the next line`. – Nicholas Tower Jun 06 '22 at 01:58
  • Thanks! I'm getting this `SyntaxError: await is only valid in async functions and the top level bodies of modules` Do I need an Immediately invoked function expression here? How would that look? – SevenSouls Jun 06 '22 at 02:11
  • As it says, you can only use await inside an async function. So most of the time, the fix is to mark the function that this code is in as `async`. Occasionally, an IIFE can be useful to create an ad-hoc async function, but I wouldn't use that as the default solution. – Nicholas Tower Jun 06 '22 at 02:20
  • Got it thanks a lot! Still getting used to Async programming. – SevenSouls Jun 06 '22 at 02:22

0 Answers0