Coder Social home page Coder Social logo

make-synchronous's Introduction

make-synchronous

Make an asynchronous function synchronous

This is the wrong tool for most tasks! Prefer using async APIs whenever possible.

The benefit of this package over packages like deasync is that this one is not a native Node.js addon (which comes with a lot of problems). Instead, this package executes the given function synchronously in a subprocess.

This package works in Node.js only, not the browser.

Install

npm install make-synchronous

Usage

import makeSynchronous from 'make-synchronous';

const fn = makeSynchronous(async number => {
	const {default: delay} = await import('delay');

	await delay(100);

	return number * 2;
});

console.log(fn(2));
//=> 4

API

makeSynchronous(asyncFunction)

Returns a wrapped version of the given async function which executes synchronously. This means no other code will execute (not even async code) until the given async function is done.

The given function is executed in a subprocess, so you cannot use any variables/imports from outside the scope of the function. You can pass in arguments to the function. To import dependencies, use await import(โ€ฆ) in the function body.

It uses the V8 serialization API to transfer arguments, return values, errors between the subprocess and the current process. It supports most values, but not functions and symbols.

Related

make-synchronous's People

Contributors

mesqueeb avatar richienb avatar sindresorhus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

make-synchronous's Issues

node version

is it possible to get this running with newer node versions?

I does not work with a current angular project.

Why not sleep-synchronously until the async call is done?

Why not sleep-synchronously until the async call is done?

Something like

const sleepSynchronously = require('sleep-synchronously');

function makeSynchronous(fn) {
  let done = false;
  let _result;
  let _error;

  (async () => {
    try {
      _result = await fn();
    } catch (error) {
      _error = error;
    }
    done = true;
  })();

  while (!done) {
    sleepSynchronously(100);
  }

  if (_error) {
    throw _error;
  }

  return _result;
}

[feat] CJS

https://github.com/sindresorhus/make-synchronous#make-synchronous

This is the wrong tool for most tasks! Prefer using async APIs whenever possible.

  • This is not a generic purpose package
  • under the philosophy of special handling for special case

So, I think it might be better to have commonjs version of this package.

I think there are still a lot of real world cases need make-synchronous within CJS context, for example

So, as this is not a generic purpose package, I think it's worth to get CJS back.

  • dual package
  • or conditional exports
  • or backport

BTW, what are the real world use case of make-synchronous within ESM context?

Can't execute mariadb function wrapper

I am trying to build a wrapper around a mariadb function, but calling it fails with error:
What am I doing wrong?

S:\Development\mariadb\node_modules\make-synchronous\index.js:61
throw error;
^

ReferenceError: ConnOptions is not defined
at createConnection ([stdin]:17:21)
at [stdin]:22:3
at [stdin]:27:6
at Script.runInThisContext (vm.js:120:18)
at Object.runInThisContext (vm.js:309:38)
at Object. ([stdin]-wrapper:10:26)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at evalScript (internal/process/execution.js:94:25)
at internal/main/eval_stdin.js:29:5
at Socket. (internal/process/execution.js:207:5)

Code:

const ms = require('make-synchronous');
const mariadb = require('mariadb');

function createConnection(opts) {
const fn = ms(mariadb.createConnection)
var conn = fn(opts)
return conn
}

var conn = createConnection({host:'localhost',user:'rudi',password:'secret'})

Accept `string` as function

The module already works with strings, only the types should be updated.

Probably type AsyncFunction = (...args: any[]) => Promise<unknown>; should be type AsyncFunction = ((...args: any[]) => Promise<unknown>;) | string

Passing parameter to first async call produces "No debugger available, can not send 'variables'"

I am calling an async function that calls a series of async functions.
First call in the series gives me the error "No debugger available...".
(createConnection)

Code:

function syncFunction(param) {
const ms = require('make-synchronous');
const fn = ms(a.asyncFunction(param))
return fn(param)
}

async function asyncFunction(param) {
var rows = []
const mariadb = require('mariadb');
var conn = await mariadb.createConnection({host: 'localhost', user: 'rudi', password:'***'});
try {
rows = await conn.query("SELECT 1 as val");
} catch (err) {
console.log('error')
throw err;
} finally {
await conn.destroy()
}
console.log(rows)
return rows
}

var res = syncFunction('example')
console.log(res)

Here is the output

const result = await ([object Promise])(...arguments_);
^^^^^^^

SyntaxError: Unexpected identifier
at new Script (vm.js:88:7)
at createScript (vm.js:261:10)
at Object.runInThisContext (vm.js:309:10)
at Object. (stdin-wrapper:10:26)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at evalScript (internal/process/execution.js:94:25)
at internal/main/eval_stdin.js:29:5
at Socket. (internal/process/execution.js:207:5)
at Socket.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1223:12)
end
[
{ val: 1 },
meta: [
ColumnDef {
_parse: [StringParser],
collation: [Collation],
columnLength: 1,
columnType: 3,
flags: 129,
scale: 0,
type: 'LONG'
}
]
]

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.