TypeScript
Promise retries with timeouts (back-off attempts)

by Benny Neugebauer

private pause(duration: number): Promise<QueryOrderResult> {
    return new Promise(resolve => setTimeout(resolve, duration))
  }

// Warning: This code might create a huge callback stack. Because it uses recursion, the call stack grows over time (when the Promise does not fulfill). This can exceed the available memory.
private async observeOrder(symbol: string, orderId: number): Promise<QueryOrderResult> {
  return this.client
    .getOrder({
      symbol,
      orderId,
    })
    .then((result: QueryOrderResult) => {
      if (result.status === 'NEW') {
        return this.pause(5000).then(() => this.observeOrder(symbol, orderId))
      } else {
        return result
      }
    })
}

// Warning: This code might create multiple Promises which will NEVER resolve (Zombie Promises). There will be 1 Zombie for every unsuccessful retry.
private observeOrder(symbol: string, orderId: number): Promise<QueryOrderResult> {
  return new Promise((resolve) => {
    const checkIfOrderIsComplete = async () => {
      const result: QueryOrderResult = await this.client.getOrder({symbol, orderId})
      if (result.status === 'NEW') {
        setTimeout(() => checkIfOrderIsComplete(), 5000)
      } else {
        resolve(result)
      }
    }

    checkIfOrderIsComplete()
  })
}