spadel
spadel

Reputation: 1046

How to export a variable in JavaScript within a function?

I have the following function:

export function request(
  searchKey,
  apiEndpoint,
  path,
  params,
  { additionalHeaders } = {}
) {
  const method = "POST";
  return _request(method, searchKey, apiEndpoint, path, params, {
    additionalHeaders
  }).then(response => {
    return response
      .json()
      .then(json => {
        var my_json = update(params)
        const result = { response: response, json: json };
        return result;
      })
  });
}

I want to export the variable my_json to another .js file. I already tried with export { my_json }, but it only works if I do that on the top of the document, which doesn't work in my case. Does anyone have an idea?

Upvotes: 0

Views: 130

Answers (1)

AyushKatiyar
AyushKatiyar

Reputation: 1030

You can't export a variable which is inside a function but you can definitely get the value stored in my_json by the help of a callback function written in another javascript file. Try using:

export function request(
  searchKey,
  apiEndpoint,
  path,
  params,
  { additionalHeaders } = {},
  callback
) {
  const method = "POST";
  return _request(method, searchKey, apiEndpoint, path, params, {
    additionalHeaders
  }).then(response => {
    return response
      .json()
      .then(json => {
        var my_json = update(params);
        callback(my_json);
        const result = { response: response, json: json };
        return result;
      })
  });
}

and in the other file define a function callback like:

function callback(data){
    // assign this data to another variable so that one can use it
    console.log(data)
}

and while calling the request function add one more argument as callback.

Hope this helps.

Upvotes: 1

Related Questions