Increase by one using async/await in Node.js JavaScript

Is it possible to output the result from the 'three' function to console.log in the 'one' function?

one = async (number) => { 
        console.log(`we received ${number}`)
        await two(number)
        console.log('the number three should be displayed here')
    }   

two = async (number) => {
    number++
    console.log(`I obtained ${number}`)
    await three(number)
}

three = (number) => {
    number++
    console.log(`final step is ${number}`)
}

one(1)

Answer №1

The connected functions are intended to yield an increased number. It's worth noting that as two promptly returns the result of calling three, it doesn't need to be marked as async. You can simply change it into a regular function that delivers three's Promise:

one = async (number) => { 
        console.log(`we received ${number}`)
        const resTwo = await two(number)
        console.log('the number three should be here ' + resTwo)
    }   

two = (number) => {
    number++
    console.log(`I got ${number}`)
    return three(number)
}

three = (number) => {
    number++
    console.log(`last but not least ${number}`)
    return number;
}

one(1)

Answer №2

let count = 0;
async function returnNumber() {
  return Promise.resolve(count++);
}

returnNumber(count).then(alert); // 0
returnNumber(count).then(alert); // 1
returnNumber(count).then(alert); // 2
returnNumber(count).then(alert); // 3

We can use a promise to explicitly return a value

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

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

Utilizing numerous occurrences of my personalized Angular JS Directive within the identical form

I've been struggling to find a solution for this particular issue. On my webpage, I have two instances of a directive that are supposed to set values for two different text fields. However, when I select one value, the other field automatically chang ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Chrome extension causing delays in rendering HTML on webpage

Currently, I am developing a script (extension) that targets a specific HTML tag and performs certain actions on it. The challenge I am facing is that this particular HTML tag gets dynamically loaded onto the page at a certain point in time, and I need to ...

When working with JavaScript, it's important to note that any reference used outside of the catch block

Our JavaScript code includes a try...catch block that functions as follows: We import the customFile using: const ourCustomClassFile = require('./customFile'); In the customFile.js file, we have defined a function const sendErrorNotification ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Error arises when uploading csv files to Node.js with Multer due to an unexpected field presence

I'm currently working on implementing a file upload feature with the use of Node.js, Vue, and Multer. Below is the Vue.js front-end code: export default { data(){ return{ selected: "How do you want to input the data?", options: [ ...

I'm struggling to concentrate and unable to type in the email field

Today while working on a website, I encountered something strange. In the footer section of the site, there is a quick contact form. However, I noticed that in Firefox, I am unable to focus on the email field. Surprisingly, this issue does not occur in Chr ...

How can I implement a progress bar that mimics an exchange platform behind data-table components? [Using Vue and Vuetify]

I am working on a cryptocurrency exchange book simulator and I am trying to implement a progress bar that will be displayed behind the values in a table. https://i.stack.imgur.com/9gVsY.png This is the template for my data-table: < ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message StaleElementReferenceError: stale element reference: element is not attached to the page document every time I attempt to extract the text from a page body using Selenium. Numerous attempts h ...

When using jquery.hide() and show(), the content within the div disappears momentarily before reappearing

Hello! I am experiencing an issue where the content of my div disappears after using a jQuery hide() and show() function. It seems to be gone. <li class="gg3"><a class="link" href="#" data-rel="content3">Link1</a></li> <div clas ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

Pass data from a JavaScript function to Objective-C in Xcode by returning an array

How can I retrieve an array of strings from Javascript in my iPhone app code? I am calling a Javascript function, and once it completes, I need to send the array of strings back to the Objective-C code. What is the best way to return the array and how can ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

What is the best approach to sending numerous queries from a single endpoint using Express?

I am attempting to perform multiple database queries and create an object that stores each response from the database in a specific field. Below is the code I have written: router.post('/search', (req, res) => { var collection = db.get(). ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...