[ Traslation service ] Task 3 problem

Hello, I’m George, and I don’t understand the mecanism of this exercise. I don’t know how to integrate the calls on a Promisse… I have consult AI but I don’t undestand yet.
Any help?
(My english is so bad, I know and working on it, apologies)

Hello there!

From the instructions we get:

  • If api.request does not return an error, resolve with undefined
  • If api.request returns an error, retry at most two times
  • If you run out of retries, reject with the last error received

So let’s build that!

The function we have is:

this.api.request(text, callback)

We know this because of the api.js tab at the top of the editor / the api.js file.

JSDoc of the request function

It takes a text to translate, and a callback. The callback will be called without value if the request succeeded and has an error if the request failed.

The only thing left is knowing how to create a new promise, or in JavaScript terms: how to promisify a callback. The general structure to promisify a function execute is:

const myPromise = new Promise((resolve, reject) => {

  // the execute function takes a callback
  execute((error) => {

    // If the callback has an error, reject the promise
    if (error) { 
      reject(error)
    } else {
      // otherwise we are done
      resolve();
    }
  })

}); 

This should be enough information to turn the api.request into a promise. If not:

const myPromise = new Promise((resolve, reject) => {
  this.api.request(text, (result) => {
    result ? reject(result) : resolve();
  })
});

Now things can be chained, which we can only do at most twice because:

It should perform no more than 3 calls for the same request

There are many ways to solve that. The structure I propose is:

return doTheThing
  .catch(() => {
    // there was an error in doTheThing
    
    // somehow make a new promise that does the thing again
    return doTheThingAgain
  })
  .catch(() => {
    // there was an error in doTheThingAgain
    
    // somehow make a new promise that does the thing again
    return doTheThingOneLastTime
  })

This is at most 3 calls:

  • doTheThing
  • doTheThingAgain
  • doTheThingOneLastTime

This way, if doTheThingOneLastTime also fails, the error is returned (the entire chain is rejected), which is exactly what you want. If doTheThing, doTheThingAgain or doTheThingOneLastTime result in a successful request, then all the catch callbacks are skipped, and the entire chain is resolved.

Can you try to work out how to implement this?

1 Like

Thanks a lot!
I wasn’t using the then/catch structure, and I hadn’t realized you could use it just for error handling. I also didn’t really trust using a constant for the promise — but I think that was the key for me to finally get it.