0

I had an interview today, I cannot say who, and the question was a JavaScript Promise question I could not figure out.

Essentially you are given a class in which all the methods can be chained off of one another. The kicker is that each function takes any amount of time and that the next function needs to wait until the last function is executed to start.

The chaining is straightforward because you can just return a reference to the class, however the Promise is what threw me off.

I had come up with the idea of a queue which make sense, but I still couldn't figure out how to fully complete a Promise and then return something from the class method.

Can anyone explain, below is an example of the code.

Note: it does not work it is just an example of the sample code. this.resolvePromise(); is just a stub for what is supposed to happen.

const p = new Promise((resolve, reject) => {
  resolve('Success!');
});

class X {
  hello(){
    console.log("Hellow");
    this.resolvePromise();
    return this;

  }
  bye(){
    console.log("Bye");
    this.resolvePromise();
    return this
  }
}

let x = new X();
x.hello().bye();
Grant Herman
  • 923
  • 2
  • 13
  • 29
  • 1
    Something like this: [How to sleep a method in javascript method chaining](https://stackoverflow.com/q/66275674)? – VLAZ Feb 27 '21 at 01:08
  • Would you not just have each method return a Promise, which resolves to the instance itself? Then you can do `obj.method1().then(me => me.method2())` and so on? – Robin Zigmond Feb 27 '21 at 01:12
  • @RobinZigmond that interface is not very fluent – VLAZ Feb 27 '21 at 01:12
  • True, it's just the first thing I came up with :) – Robin Zigmond Feb 27 '21 at 01:14
  • @GrantHerman It's sort of hard to tell what parts of the code are editable and which aren't. Is the deal you implement the class and `new X().hello().bye();` is the contract you have to fulfill, or is that `new X().hello().bye()` also open for negotiation? What parts of the `X` class can you adjust? – ggorlen Feb 27 '21 at 01:15

0 Answers0