ChrisCho-H / bitcoin-sdk-js

Bitcoin TypeScript/JavaScript Library for NodeJS, Browser and Mobile. Segwit & Taproot support.✨
MIT License
30 stars 4 forks source link

Why async? #2

Open vostrnad opened 1 month ago

vostrnad commented 1 month ago

Why does every function return a Promise? As far as I can tell, the library doesn't actually need any async functions.

ChrisCho-H commented 1 month ago

Hi, thanks for opening an issue!

As the library itself doesn't relate to any I/O bound task(i.e. network, disk), it's true that it doesn't benefit much.

However, as far as I know, there are still some benefits to use async.

const test = async () => { const tx = new bitcoin.Transaction(); for (let i = 0; i < 100000; i++) { // not 'await' async func tx.addInput({ txHash: 'fd274afbd216c1b72fbe26fb536e312391b1f750eff6c58bce8bedc48dd26693', index: i, value: 1000, }) } // 'sync' will be printed console.log('sync'); // 'addInput' is not finished yet, so tx does not have any input, // because inside 'addInput' it awaits some other function before insert input in tx. console.log(tx); }

test();


If you would like to finish some other task first after call async function, it's beneficial not to "await". If that task is related I/O bound task, it would help a lot. It would provide a lot of flexibility in application level.
- While NodeJS runtime uses mostly single main thread, there's a thread pool either to execute cpu intensive job(crypto) or File I/O job(because underlying OS does not support async for it)! Although the library doesn't directly uses `node::crypto`, I guess when doing crypto related task it might use it. In that case, it does matter to asynchronously execute function to benefit from parallel multi-thread.
- Lastly, I guess there would be more possible benefits by providing `async`, while it does not have any disadvantage except it might produce some boilerplate(if dev want to use async function only in synchronous way, must resolve it).