the order of performing asynchronous a few methods in JavaScript

the order of performing asynchronous a few methods in JavaScript

asynchronous programming javascript
async/await javascript
javascript wait for function to finish
javascript asynchronous callback
javascript wait for asynchronous call to finish
asynchronous javascript w3schools
callback function javascript
javascript synchronous function

I have a three method in JavaScript NodeJS Sequelize. Calling them is saved as follows:

setTransferHistory(senderId, recipientId, amountMoney, transferTitle);
setWidgetStatus(senderId);
setWidgetStatus(recipientId);

Each method does update or select in the mysql database. It is very important that they are made in this order and it is not always so.

I know that solving this problem uses the word then in the setTransferHistory method, thus:

  function setTransferHistory(
    senderId,
    recipientId,
    amountMoney,
    transferTitle,
  ) {
    Transaction.create({
      id_sender: senderId,
      id_recipient: recipientId,
      date_time: getTodayDate(),
      amount_money: amountMoney,
      transfer_title: transferTitle,
    }).then(() => {
      setWidgetStatus(senderId);
      setWidgetStatus(recipientId);
    });
  }

...but I don't want these two methods to be included in this method. I would like to just write it one below the other.


Since Transaction.create returns a Promise, you can have setTransferHistory returns that, and defer the execution of setWidgetStatus after setTransferHistory's promise is fulfilled. So with:

const setTransferHistory = (
  senderId,
  recipientId,
  amountMoney,
  transferTitle
) =>
  Transaction.create({
    id_sender: senderId,
    id_recipient: recipientId,
    date_time: getTodayDate(),
    amount_money: amountMoney,
    transfer_title: transferTitle
  });

You can have either:

setTransferHistory(/* args ... */).then(() => {
  setWidgetSatus(senderId);
  setWidgetSatus(recipientId);
});

Or use await - that works with promise, as soon you use it in an async function, setTransferHistory doesn't need to be async:

async function foobar() {
  await setTransferHistory(/* args ... */);

  setWidgetSatus(senderId);
  setWidgetSatus(recipientId);
}

Of course at this point you could just use directly Transation.create, but it's up to you, if you want to add a layer of abstraction.

Asynchronous Programming :: Eloquent JavaScript, A function doing asynchronous work typically returns before the work is done, having arranged for a callback to be called when it completes. So we need some​  In this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and JavaScript. You should understand these concepts before working through the other articles in the module.


All you need to do is return the promise from setTransferHistory that create gives you, so that you can invoke then on the result of the call:

function setTransferHistory(senderId, recipientId, amountMoney, transferTitle) {
  return Transaction.create({
//^^^^^^
    id_sender: senderId,
    id_recipient: recipientId,
    date_time: getTodayDate(),
    amount_money: amountMoney,
    transfer_title: transferTitle,
  });
}

setTransferHistory(senderId, recipientId, amountMoney, transferTitle).then(() => {
//                                                                   ^^^^^
  setWidgetStatus(senderId);
  setWidgetStatus(recipientId);
});

Understanding Ordering With JavaScript Async Methods, This makes sense from a performance point of view, some async methods might never need the change of context, so just in time async. To  In asynchronous programs, you can have two lines of code (L1 followed by L2), where L1 schedules some task to be run in the future, but L2 runs before that task completes. You can imagine as if you are eating at a sit-down restaurant. Other people order their food. You can also order your food.


Nowadays when dealing with promises, good practice is using the async/await keywords. They basically allow you to run your asynchronous code in a synchronous manner. Using them, your code would look like this :

async function setTransferHistory(senderId, recipientId, amountMoney, transferTitle) {
     return await Transaction.create({
       id_sender: senderId,
       id_recipient: recipientId,
       date_time: getTodayDate(),
       amount_money: amountMoney,
       transfer_title: transferTitle,
     });
}

await setTransferHistory(senderId, recipientId, amountMoney, transferTitle);
setWidgetStatus(senderId);
setWidgetStatus(recipientId);

The await keyword stops the execution of the function and waits for the result of Transaction.create() and async is needed in order to use await inside the function.

Hope this helps.

Introduction to Asynchronous JavaScript | Pluralsight, This guide will explain what asynchronous code is, some of the difficulties of For example, if you order a steak, and then I order a glass of water, I will likely In JavaScript, we can create a callback function that we pass into an Similarly, when doing an AJAX call, it is possible to set an option to make the  Note: await works with a promise so your function has to return a promise that is resolved/rejected when the asynchronous operation is complete. Also, note that in order to use await, the containing function must be declared async. Run asynchronous operations in parallel and use Promise.all() to collect results in order


How to run async JavaScript functions in sequence or parallel, Let's imagine we need to make a series of asynchronous function calls. They could be anything. As an example, we'll make up a couple of  The statements above will execute in order, outputting “First”, “Second”, “Third” to the console. That’s because it’s written synchronously. Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting.


Making asynchronous programming easier with async and await , More recent additions to the JavaScript language are async functions and the And if you want to add error handling, you've got a couple of options. your code carefully, and bear this in mind if performance starts to suffer. Asynchronous Callbacks. The earliest and most straightforward solution to being stuck in the synchronous world is using asynchronous callbacks (think setTimeout()).. Let’s use a database request


JavaScript Promises and Async/Await: As Fast As Possible™, Using Web APIs, some JavaScript jobs can be transferred to other threads. logs will show up in the order of the least delay, because callback function statement to each function that will perform an async task (setTimeout). To declare an async class method, just prepend it with async: class Waiter { async wait() { return await Promise.resolve(1); } } new Waiter() .wait() .then(alert); // 1 The meaning is the same: it ensures that the returned value is a promise and enables await .