Coder Social home page Coder Social logo

suspensify's Introduction

Suspensify

Easy way to convert any async function to suspended function

yarn add suspensify

Demo: https://pie6k.github.io/suspensify/

import React, { Suspense } from 'react';
import { render } from 'react-dom';
import { suspensify } from 'suspensify';

// first - let's say we have some regular, async function
function getHelloWithDelay(name: string, delay: number) {
  // just a promise that returns a string after some delay
  return new Promise<string>((resolve) => {
    setTimeout(() => {
      resolve(`Hello, ${name}`);
    }, delay);
  });
}

// now we convert it to suspended function
const [getSuspendedHello] = suspensify(getHelloWithDelay);

// now we can just use it inside any component like it is sync function

// let's create some simple component
interface DelayedHelloProps {
  delay: number;
  name: string;
}

function DelayedHello({ delay, name }: DelayedHelloProps) {
  const helloString = getSuspendedHello(name, delay);
  return <div>{helloString}</div>;
}

// last step is to create suspense loading fallback
function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <DelayedHello name="Bob" delay={1000} />
    </Suspense>
  );
}

// and start the app
render(<App />, document.getElementById('app'));

suspensify's People

Contributors

pie6k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.