Execute Async Server Function from Client Side

Execute server’s asynchronous functions from client-side

Often it happens while writing web application that you need to make HTTP requests to fetch, create, update or delete data from database.

With RealSync, you wouldn’t have to remember all those HTTP endpoints, and perform actions as if you’re executing server functions from client-side.

RealSync uses web socket to make contact with the server and execute asynchronous function and returns promise which you can await in the client side. Here is an example of a server code, you can connect it with Express or Koa, if you want.

const http = require('http')

const app = http.createServer()

const  RealSync  = require('../packages/server/lib')

const realsync = new RealSync(app, '*')

function sleep(ms) 
    return new Promise((resolve) => setTimeout(resolve, ms))

realsync.register('add', async (a, b) => 
    const sum = a + b

    // Sleep 2 seconds, then return the answer [async]
    await sleep(2000)

    return 'sum = ' + sum


app.listen(8080, () => 

This will register a service “add” in realsync and accept two parameters, a and b.

And here is a client demonstration using React:

import  RealSync  from '@realsync/react'

const realsync = new RealSync('http://localhost:8080')

function App() 
    const Sum = async () => 
        const sum = await realsync.service('add', [2, 3])
    return (
        <button onClick=Sum>Sum</button>

export default App

I would love to have feedback forum you guys. I’ve more to add in this library.

GitHub: https://GitHub.com/xencodes/realsync

Source link