anticipating the response of JS callbacks on the main thread

I am currently in the process of setting up an authentication and account creation page for my website using Express and SQLite. I am facing a challenge with my function to add users, as it involves multiple callback steps interacting with the database. I would like to ensure that all these steps have completed before ending the function so that I can send data back to the front end through the express response. This data would include any potential error codes from the database (such as user already exists) and the actual user data upon successful connection.

function addUser(username,password)
{
  var db = new sqlite3.Database('./database/users.db',sqlite3.OPEN_READWRITE, (err) => {
    if (err) {
      console.error("Open error code : "+err.errno+" ; message : "+err.message);
    }
  });
  var statement=db.prepare("INSERT into users(username,password) VALUES(?,?)")
  statement.run(username,password,(err)=>{
    if (err) {
      console.error("Run error code : "+err.errno+" ; message : "+err.message);
    }
  });
  statement.finalize((err)=>{
    if(err)
    {
      console.error("Finalize error code : "+err.errno+" ; message : "+err.message);
    }
  })
  db.close()
}

The desired server response format is as follows:

app.post('/addUser',jsonParser,(req,res)=>{  
  res.status(200).send(JSON.stringify({error : addUser(req.body.username,req.body.password)}))
});

The current issue revolves around ensuring that any error generated within the steps of the addUser() function are properly returned.

I attempted various methods such as declaring variables to store errors and user data but faced challenges with the asynchronous nature of callbacks.

A solution was found by incorporating promises and then() functions as illustrated below:

async function addUser(username,password)
{
  // Function implementation using await and promises
}

app.post('/addUser',jsonParser,(req,res)=>{
  addUser(req.body.username,req.body.password).then((value)=>{
    console.log(value)
    res.status(200).send(JSON.stringify(value))
  })
});

Tests have shown that working with objects like data{} within the addUser() function is crucial for manipulating variables across the code effectively.

Answer №1

Perhaps you could attempt:

async function addUser() { return data}
var data = await addUser();
//blocking if resolve and next ....
app.post({send:data})

or

async function addUser() { return data}
addUser().then((data)=>{app.post({send:data})});
   //non-blocking and next ....

or

var resp = {}
var response= new Promise((resolve)=>{resp.resolve = resolve})

async function addUser() { 
example.run(a)=>{
resp.resolve(a);
}}
response.then((data)=>{app.post({send:data})});

or

async function* reader() {
  while (true) {
    const value = yield;
    console.log(value, '-----generator');
  }
}

const read = reader();
var i =0

read.next(0) //first value not return

async function create(val) {

await read.next(val); 



}

function addUser() {

example.run((a)=>{
create(a)
})

or

async function addUser() { 
example.run(a)=>{
readData(a)
}}

async function readData(val) {
app.post()
}

or RxJS library test

the first locks the code underneath inside the function it resides in, the second doesn't wait inside then

------ edit

All the necessary information can be accessed on this page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve. This is located in the overview tab. These are fundamental concepts of JavaScript.

async function addUser() {
  var func = ()=>{return Promise.resolve('data from callback');}
  return func()
  }
addUser().then((val)=>{console.log(val)})

Async post function in NodeJS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Adjust the code to enhance the functionality of web components in Sharepoint

I recently came across some code online that I'm trying to modify in order to add an expanding button next to a web part on my Sharepoint site. However, the problem is that by default, all web parts are already expanded and require a click to collapse ...

Tips for creating a filter in React JS using checkboxes

In my current situation, I have a constant that will eventually be replaced with an API. For now, it resembles the future API in the following way: const foo = { {'id':1, 'price':200, 'type':1,}, {'id':2, &apo ...

Transmit information from JavaScript to a servlet and receive a response in return

I'm new to using ajax and JavaScript. Currently, I have a simple jsp page containing HTML and an accompanying JavaScript file with all my functions defined. One of these functions sends JSON data to a servlet and now I need assistance in receiving th ...

Automatically navigate to a new page once form submission is successful and posts have

Within my webpage, I have an attribute called onSubmit that is responsible for handling the submit event. The functionality of the submit and the page element are outlined below. Upon submission, the first step is to initiate a post request for a ruleset, ...

I am unable to view the cookies being sent by expressjs (passportjs) in the browser

After developing a React app with Vite, I encountered an issue with passportjs authentication where no cookies were visible in the browser. Despite trying various solutions, the problem persisted. As a last resort, I created a new React app using the creat ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Angular directive Jasmine testing malfunctioning

I'm facing a challenge while trying to execute a simple test for an Angular directive, as it is not running successfully. The code I have written so far is causing jshint to display the error message: 'inject' is not defined, and the test is ...

Exceeded the maximum stack size limit

let newArray = []; $('#select_students option:selected, #cc_select_students option:selected').each(function(){ newArray.push(item); }); ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

JavaScript code using the Jquery library to retrieve the following article from 'cached memory'

I am aware of the easier CSS options for my question, but I am determined to learn JS (Jquery), so please bear with me. My plan: Menu-items are connected to articles within my content division. Initially, only the first article (#intro) is displayed. All ...

Issue with Generating divs dynamically in Ionic Framework

I'm currently working on dynamically generating a board game using divs in AngularJS, like so: HTML: <div class="boardgame" ng-repeat="square in board"> <div class="square"></div> </div> JS: $scope.board = [ {value: ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

Cordova does not support the transform property

In the process of creating an Apache Cordova app using the Ionic framework and working with Phonegap Build, I encountered a challenge. The main page of my app features rows of icons that appear like this: https://i.sstatic.net/7LE7r.png However, there is ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Adjust the font color of the X and Y axis

Is there a way to customize the color of the X and Y axes labels in Chart.js? I attempted to use the fontColor property within scaleLabel, but I suspect I may be placing it incorrectly? I experimented with placing it under scale as suggested by the source ...

Clearing the canvas completely with CamanJS: a step-by-step guide

I need some help with my CamanJS photo editing app. Everything is working perfectly except for one issue - when a user uploads a new image and applies a filter, the canvas reverts back to the previously uploaded image. Even though I am using the revert() f ...

Implementing a clickable image using an anchor tag in JavaScript

I need to enhance my image tag in JQuery by adding an anchor tag alongside it. How can I accomplish this using JavaScript? Here is what I attempted: var imgg = document.createElement("img"); imgg.className='myclass'; $( ".myclass" ).add( "<a ...