commit 04acc46a9d159c1449fd51e7cff14905df7740ec Author: thecookingsenpai Date: Mon Dec 25 13:25:26 2023 +0100 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..162b595 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# AstraSync + +![image](https://user-images.githubusercontent.com/67682496/210121921-9967cbc8-5b72-47e6-b440-77f479346803.png) + + +## A way to execute asynchronous tasks within synchronous contexts + +AstraSync provides a way to execute asynchronous tasks within synchronous contexts, for example calling an async method from a sync method and waiting for it to resolve before continuing. + +## Installation + + npm install -g astrasync + +## Usage + + const astraSync = require('astrasync'); + + function syncMethod() { + //... your code + asyncMethod().then(function (result) { + promiseStatus.value = result; + promiseStatus.resolved = true; + } + waitForAsync(5); // wait 5 seconds before timing out + } + +## Disclaimer + +This module is highly experimental diff --git a/astrasync.js b/astrasync.js new file mode 100644 index 0000000..fb99999 --- /dev/null +++ b/astrasync.js @@ -0,0 +1,42 @@ + + +function sleep(ms) { + var start = Date.now(), + now = start; + while (now - start < ms) { + now = Date.now(); + } + } + +// SECTION Exported things +var promiseStatus = { + value: null, + resolved: false +} + +// NOTE Checking for (timeout) seconds the promise status +function waitForAsync(timeout) { + var timer = 0 + while(!promiseStatus.resolved) { + // Sleeping half second before checking again + sleep(100) + // Increasing timeout timer + timer += 1 + // In case of timeout, return false and register unsolved on 99 + if (timer >= (timeout*10)) { // Multiply by 10 because of the 100ms sleep + promiseStatus.value = null + promiseStatus.resolved = false + return false + } + } + // If promise status is resolved, return the value + let value = promiseStatus.value + promiseStatus.value = null + promiseStatus.resolved = false + return value + +} +// !SECTION Exported things + +// Exporting the functions +export { waitForAsync, promiseStatus } \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..b5cd8da --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "astrasync", + "version": "1.0.1", + "description": "Make possible to use async methods in sync methods", + "main": "astrasync.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/thecookingsenpai/desync.git" + }, + "keywords": [ + "sync", + "async", + "desync" + ], + "author": "thecookingsenpai", + "license": "ISC", + "bugs": { + "url": "https://github.com/thecookingsenpai/desync/issues" + }, + "homepage": "https://github.com/thecookingsenpai/desync#readme" +}