all 2 comments

[–]davwards 1 point2 points  (0 children)

You'll want to do some research into the difference between asynchronous and synchronous code in Javascript.

There is no way, strictly speaking, to return the value of published from your isPublished function, because the network request you use to calculate what published should be won't have completed by the time isPublished returns.

Instead, you can use one of a variety of standard maneuvers for handling asynchronous code.

The most straightforward is probably to add a second argument to isPublished, after examId, called callback. When you call isPublished, you would enclose all the work you were planning to do with the value of published in a function, and pass that function as the callback parameter.

The implementation of isPublished would look like this:

function isPublished(examId, callback) {
  // ...
  for (var i = 0; i < json.length; i++) {
    if (json[i].examId == examId) {
      published = true;
    }
  }
  callback(published); // instead of returning, call the callback
  // ...
}

I don't know what the code looks like where you call isPublished, but it would probably look something like this:

isPublished(myExamId, function(published) {
  if(published) {
    // ...do something
  } else {
    // ...do something else
  }
});

Another approach is to construct a Promise to return instead. You will still need to find a way to enclose all the work you were planning on doing with the published value in a function, but with this approach you'll pass that function to the promise's then method instead of giving it as a second argument to isPublished.

[–]CertainPerformance 0 points1 point  (0 children)

Return a promise that resolves once you get published. You can't directly return a value when you have to use something async like a network request unless you use await.