0
votes

so I have two js files file1.js

const { expect } = require("chai");
const { createEnrollment } = require("../utils/file2")
describe('create enrollment', function () {
   it('enroll the user into the system',  async function () {
        var x = createEnrollment(inputParams)
        console.log(x)

    })

File2.js

const fetch = require('node-fetch')
async function createEnrollment(params) {
fetch('URL').then(function (response) {
response.json().then(function (text) {
  var val = text;
  console.log("VALUE " + val.userId)
  return text;
});
module.exports = { createEnrollment }

But when I run this code console.log(x) is undefined and is running before createEnrollment is complete. I made the function async but still the value returning is undefined.

2

2 Answers

1
votes

Fetch is an asynchronous function, and will therefore need to be used with either async/await, or promise chaining.

Example:

async function callAPI(url) 
{
  let response = await fetch(url);
  let data = await response.json()
  return data;
}
0
votes

There is no need to declare a function as async if you are not awaiting something inside of it.

You have to wait for the asynchronous functions to resolve. In order to do that (without async/await) you need to have access to the promise to wait for it to resolve. So, you need to return the promise in the createEnrollment method:

function createEnrollment(params) {
    // Note the return before the fetch!
    return fetch('URL')
        .then(function(response) {
            return response.json();
        })
        .then(function(text) {
            var val = text;
            console.log("VALUE " + val.userId)
            return text;
        });

Now in your test, you can wait for the promise to be resolved:

describe('create enrollment', function () {
    it('enroll the user into the system', function () {
        // The return here is intended for the test to wait until the promise is fullfilled.
        return createEnrollment(inputParams).then(function(x) {
            console.log(x);
        });
    });
});

Alternatively, if you use async/await syntax:

async function createEnrollment(params) {
    const response = await fetch('URL');
    const text = await response.json();
    return text;
}
describe('create enrollment', function () {
    it('enroll the user into the system', async function () {
        const x = await createEnrollment(inputParams);
    });
});