Start learning free

LESSON 106 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Try Again, a Few Times in JavaScript

Practice

Many failures of another service last only a moment: it restarts, or one of its servers hiccups, and the next request works. So before giving up, your shop can retry: ask again, a few times. It must also stop at some point, or a service that is really down would keep the customer waiting forever.

A retry is a while loop with a counter. Here a shop asks a news service at most 2 times:

let attempt = 1;
let reply = await fetch(NEWS + "/headlines", { signal: AbortSignal.timeout(1000) });
while (reply.status >= 500 && attempt < 2) {
  attempt = attempt + 1;
  reply = await fetch(NEWS + "/headlines", { signal: AbortSignal.timeout(1000) });
}

Only answers of 500 or more are worth another try: they are the other service's own trouble, and they often pass. A 404 stays a 404 however often you ask. A timeout is not retried either: a slow supplier has already cost the customer a second.

The checks make the supplier fail on purpose: POST /check/supplier-down with {"times": 2} makes its next 2 calls answer 500. Your shop must answer:

(the supplier will fail its next 2 calls)
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
(the supplier will fail its next 4 calls)
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering", "tries": 3}
GET /products/3/supplier-stock  →  200  {"product_id": 3, "supplier_stock": 8}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}
(the supplier will be slow once)
GET /products/1/supplier-stock  →  504  {"error": "The supplier took too long"}

Your task: in the route for /products/:productId/supplier-stock, count the calls in a variable tries, call the supplier again while it answers 500 or more and fewer than 3 tries were made, and add tries to the 502 answer.


Assignment
Follow the Coding Tutorial to add retries, with a limit, to the supplier call in the supplier-stock route.


Hint
Start tries at 1 with let, above the try block: the first call is try number 1. Join the loop's two conditions with &&. Inside the loop, add 1 to tries and make the same call again.


STEP 1 OF 5
    Ctrl + Enter to check

    Svc Retries in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free