0

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?

7
  • You can create global variable and then export it at the end. But what you are asking is not possible. Commented Jul 10, 2020 at 18:27
  • What is the exact scenario that you are trying to solve? Commented Jul 10, 2020 at 18:30
  • did you try store your function into a variable?: export let request = () => {} Commented Jul 10, 2020 at 18:30
  • You want to build a service Commented Jul 10, 2020 at 18:30
  • I am using elasticsearch in order to build a search engine. Unfortunately elasticsearch doesn‘t provide the functionality that I need and it has some bugs when I modify it according to my needs. So basically, I want to override the output of the Connector API, which is in another file, with the json stored in my_json. I create it at that point, because there are the relevant parameters that I need in order to build my json file. Commented Jul 10, 2020 at 20:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.