ts-coroutines
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

TypeScript Coroutines

This package provides a coroutine function that allows you to write asynchronous code in a synchronous manner, using TypeScript's Generator functions.

Installation

You can install ts-coroutines with npm:

npm i ts-coroutines

Usage

First, import the coroutine function from the ts-coroutines package:

import { coroutine } from 'ts-coroutines';

Then, create a generator function where yield is used to pause and resume the execution:

const result = coroutine(function* () {
  const response = yield fetch('https://api.example.com');
  const data = yield response.json();
  return data;
});

The coroutine function returns a promise that resolves with the value returned from the generator function.

Error Handling

Errors can be handled inside the generator function with a try-catch block:

coroutine(function* () {
    try {
        const result = yield new Promise((_, reject) => setTimeout(() => reject('Error'), 500));
        console.log(result);
    } catch (error) {
        console.error(error);  // 'Error'
    }
});

If an error is thrown and not caught inside the generator function, it will reject the promise returned by the coroutine function.

Package Sidebar

Install

npm i ts-coroutines

Weekly Downloads

0

Version

1.0.2

License

ISC

Unpacked Size

5.05 kB

Total Files

8

Last publish

Collaborators

  • josharsh