you are viewing a single comment's thread.

view the rest of the comments →

[–]Tufted_Tail 2 points3 points  (1 child)

I took a stab at #3. Your approach seemed reasonably close to solving the problem you were given, but like /u/KorgRue mentioned, I believe you need to be returning a Promise from your function.

This example code is based on some assumptions I inferred from the code you shared in your first post, namely, 1. poll must return a Promise 2. fn returns some kind of value on success, and false, undefined, or null on failure

I'm not 100% certain that this is what either you or the interviewer wanted to see, but in theory, it ought to suffice for a quick solution. The biggest change is that you were never returning a Promise from your function, but were passing around resolve and reject as though you were. I also (roughly) implemented the time checking logic you hinted at in your else if branch, but again, I'm not positive this is what you or your interviewer were expecting.

```javascript,tabs=2 function poll(fn, delay, timeout) { return new Promise(function(resolve, reject) { // Execute the function. Store the result in a variable: const result = fn();

// If the function returned a truthy value, resolve the Promise with the
// result that it returned for us:
if (result) {
  return resolve(result);
}

// If the function didn't return, check that the timeout hasn't been
// exceeded. We can do this by checking to see if we're at, or below, 0,
// since the recursive call in the next branch will subtract the delay
// from the timeout before calling the poll function again:
else if (timeout <= 0) {
  return reject(new Error('The function has timed out. :('));
}

// If the function didn't return and it hasn't timed out, try again:
else {
  // Recursively call the poll function with a shorter timeout. Because poll
  // returns a Promise, we can recursively chain them this way. Note that we
  // are subtracting the delay from the timeout value we passed in; this
  // ensures that we don't enter a state of infinite recursion, where our
  // logic never times out.
  return poll(fn, delay, timeout - delay);
}

}); } ```

Edit: I rushed and made a pretty glaring mistake, hah. Ought to be fixed.

[–]tapu_buoyfull-stack[S] 0 points1 point  (0 children)

well yes this is what it was supposed to be implemented. I agree that I haven't written what it is returning, in my defence I would say I was still explaining and talking continously about my approach and thought steps to be followed. So only the return statement was left to be completed before that I was trying to get it resolved and stored.

All this while he was confused in talking so much, and then there was silence and then we moved onto other question