node.js – Using await with a node typescript function using fp-ts

I am in the process of refactoring some old code and am looking to take advantage of fp-ts for safer handling of thrown errors.

I may have to totally rewrite this section of code but I know I have a fundamental lack of experience of using fp-ts (or any functional style of programming).

The device I am updating is an IOT device and part of its function is to periodically push data (list of objects) to backend. This data is stored in temporary database on the IOT device and when it gets notification of update completion (this side can’t be changed as we are not touching backend server) it clears the relevant entries in the local database.

Chances are I will end up fully rewriting this section of code but I am interested in different potential solutions. The section question is where I call await sleep(loopIntervalSleep) followed by doing a recursive call to the function. The purpose of the sleep (node sleep-promise) is to delay calling of checkStatus for a period of time.

My question is how do I insert an await into the pipe, or insert a sequence of tasks into the pipe at this point – see test snippet below where line is marked with pre and post **.

import { pipe } from "fp-ts/lib/function"
import * as TE from "fp-ts/lib/TaskEither"
import sleep from 'sleep-promise'

const STATES = ['running', 'completed', 'failed']

const getUpdatesRandom = () => {
  const rr = Math.floor(Math.random() * 100)
  const res1 = async () => rr > 99 ? STATES[2] : rr > 70 ? STATES[1] : STATES[0]

  return TE.tryCatch(
    () => res1(),
    (err) => err instanceof Error
      ? err
      : new Error("unexpected error when authorizing request")
  )
}

const checkStatus = async (loopIntervalSleep: number, numTimes: number) => {

  const checkStatusLoop = (times: number): TE.TaskEither<Error, string> => {

    const rrr = pipe(
      getUpdatesRandom(),
      TE.flatMap(
        (item) => {
          console.log('state', item, times)
          switch (item) {
            case 'running':
              {
                if (times > 0) {
                  **await sleep(loopIntervalSleep)**
                  const resInner = checkStatusLoop(times - 1)
                  return resInner
                } else {
                  return TE.left(new Error('count exceeded'))
                }
              }
            case 'completed':
              {
                return TE.right('sync success')
              }
            default:
              {
                return TE.left(new Error('call failed'))
              }
          }
        },
      )
    )
    return rrr
  }

  return checkStatusLoop(numTimes)()
}

const result = await checkStatus(5000, 5)
console.log(result)

Read more here: Source link