1

I am invoking a functionA from another functionB in the HTML file. Basically, this file contains a couple of JS functions.

The following is functionA (getBranchAndChangeIdForSideBySideDiffView)

function getBranchAndChangeIdForSideBySideDiffView() {
  const match = parseGerritURLForSideBySideDiffView();
  const project = match[1];
  const change = match[2];
  const url = '/changes/' + '?q=' + encodeURIComponent(project) +
          '&o=CURRENT_REVISION&o=ALL_REVISIONS';

  let branch = '';
  let changeId = '';          
  coveragePlugin.restApi().get(url).then((response) => {
    branch = response[0].branch;
    changeId = response[0].change_id;
    return [branch, changeId];
    console.log('branch is', branch);
    console.log('changeId is', changeId);
  }).catch((err) => {
    console.log('Failed to get change details for code coverage:', err);
  });
}

The GET API is described here as follows (https://gerrit.googlesource.com/gerrit/+/refs/heads/stable-2.16/polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-plugin-rest-api.js#90).

And the functionB is simple which just calls functionB (also has other lines of code, the following lines of code are where I am calling functionA).

    let response = getBranchAndChangeIdForSideBySideDiffView();
    coverageData.changeId = response[0];
    coverageData.branch = response[1];
    coverageData.project = match[0];
    coverageData.change = match[1];
    coverageData.patchset = match[2];

Now, what's strange is, when I simply enter the full URL in my browser, a JSON file is downloaded. But, when this code executes in the browser, after the GET call is made, the line of execution simply moves to the end of functionB. It's like, it doesn't go inside the curly brackets. I am not sure where I am going wrong? Can anyone help me with it?

John Doe
  • 185
  • 1
  • 13
  • 3
    You don't return anything from `getBranchAndChangeIdForSideBySideDiffView` your `return` statement is in the callback. – VLAZ Sep 17 '19 at 15:09
  • 3
    Also those `console.log()` calls *after* the `return` are pointless because they will never be executed. – Pointy Sep 17 '19 at 15:09
  • So you could return the entire call to coveragePlugin.restApi.blahblah() and then your function would return a promise which you could apply another .then to to get the coverageData out. – James Sep 17 '19 at 15:13
  • Possible duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/. – connexo Sep 17 '19 at 15:14
  • These arrays already seem like a poor choice for a data-structure. There's not a single index right/unambigious in your code. `project` for example, is it `match[0]` or `match[1]`? You reference it by both indices. And what about `coverageData.changeId = response[0]; coverageData.branch = response[1];`? You return them the other way around `[branch, changeId]` *(at least if you would return)* – Thomas Sep 17 '19 at 15:20

0 Answers0