Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an Asynchronous function in Javascript?

People also ask

How do you make function asynchronous in JavaScript?

async function foo() { const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000)); const p2 = new Promise((_, reject) => setTimeout(() => reject("2"), 500)); const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead. }

What is an asynchronous function in JavaScript?

An asynchronous function is any function that delivers its result asynchronously – for example, a callback-based function or a Promise-based function. An async function is defined via special syntax, involving the keywords async and await .

How do I make a function call async?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Is it possible to run an asynchronous code in JavaScript?

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.


You cannot make a truly custom asynchronous function. You'll eventually have to leverage on a technology provided natively, such as:

  • setInterval
  • setTimeout
  • requestAnimationFrame
  • XMLHttpRequest
  • WebSocket
  • Worker
  • Some HTML5 APIs such as the File API, Web Database API
  • Technologies that support onload
  • ... many others

In fact, for the animation jQuery uses setInterval.


You can use a timer:

setTimeout( yourFn, 0 );

(where yourFn is a reference to your function)

or, with Lodash:

_.defer( yourFn );

Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.


here you have simple solution (other write about it) http://www.benlesh.com/2012/05/calling-javascript-function.html

And here you have above ready solution:

function async(your_function, callback) {
    setTimeout(function() {
        your_function();
        if (callback) {callback();}
    }, 0);
}

TEST 1 (may output '1 x 2 3' or '1 2 x 3' or '1 2 3 x'):

console.log(1);
async(function() {console.log('x')}, null);
console.log(2);
console.log(3);

TEST 2 (will always output 'x 1'):

async(function() {console.log('x');}, function() {console.log(1);});

This function is executed with timeout 0 - it will simulate asynchronous task


Here is a function that takes in another function and outputs a version that runs async.

var async = function (func) {
  return function () {
    var args = arguments;
    setTimeout(function () {
      func.apply(this, args);
    }, 0);
  };
};

It is used as a simple way to make an async function:

var anyncFunction = async(function (callback) {
    doSomething();
    callback();
});

This is different from @fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.


Edit: I totally misunderstood the question. In the browser, I would use setTimeout. If it was important that it ran in another thread, I would use Web Workers.


This page walks you through the basics of creating an async javascript function.

Since ES2017, asynchronous javacript functions are much easier to write. You should also read more on Promises.