Home > Blockchain >  Is there a way to write asynchronous code/function without any involvement of Web APIs?
Is there a way to write asynchronous code/function without any involvement of Web APIs?

Time:10-07

I know it sound stupid because javascript is single threaded but can't help thinking about a function which takes unusual amount time with no involvement from web APIs like this

console.log("start")

function apple() {
  let appleCount = 10;
  while (appleCount < 1000000) {
    appleCount = appleCount   10;
    appleCount = appleCount * 0.0000052
  }
}

apple();
console.log("end")

so is there a way to run this apple function asynchronously ... i tried running this code in browser but not getting any results... help me out..

CodePudding user response:

The only way to run something that is 100% plain Javascript like your apple() function so that it doesn't block the main thread is to run it in a different thread (in nodejs, to use a WorkerThread) or in a different process.

As you seem to know the main thread runs your Javascript in a single thread so anything that is just plain JavaScript occupies that single thread while it is running. To have it not occupy that single thread and block the event loop, you have to run it in a different thread, either a WorkerThread or run it in another process.


One can use timing tricks such as setTimeout(apple, 100) or setImmediate(apple) or even Promise.resolve().then(apple) to change WHEN the code runs (delaying when it starts), but all these timing tricks do is change when the code starts running. In all these cases, when it runs, it still blocks and occupies the main thread and blocks the event loop while its running.


FYI, there are many asynchronous operations in nodejs that are not necessarily web APIs. For example, there are asynchronous file APIs and crypto APIs that are asynchronous and non-blocking. So, your question should be modified to not refer just to web APIs, but any asynchronous API.

CodePudding user response:

so is there a way to run this apple function asynchronously?

If you don't want to wait until your apple function is complete, Then you can use Async Functions.

NOTE: Async/Promises are not true asynchronous.

console.log("start")

async function apple() {
  let appleCount = 10;
  while (appleCount < 1000000) {
    appleCount = appleCount   10;
    appleCount = appleCount * 0.0000052
  }
}

apple().then(() => console.log("Apple completed"));
console.log("end")

But If you want to run it on another thread, Then you should use Workers

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API

CodePudding user response:

You just have to return promises.

function double(num) {
  return Promise.resolve(num * 2);
}

function add5(num){
  return Promise.resolve(num   5);
}

double(1)// 2
    .then(add5)// 7
    .then(double)// 14
    .then(console.log)
  • Related