Questions tagged [async-await]

Explore the array of programming languages that embrace the asynchronous programming model with the utilization of the async and await keywords.

Puppeteer's waitForSelector function isn't behaving as anticipated

In my code snippet below: const BUSINESS = 'lalala'; await page.waitForSelector('#searchboxinput').then( page.evaluate( (BUSINESS) => { document.querySelector('#searchboxinput').value = BUSINESS }, BUSINESS) ), After setting a wait for ...

Leveraging the power of express, employing the await keyword, utilizing catch blocks, and utilizing the next

I am currently developing an express JS application that follows this routing style: router.post('/account/create', async function(req, res, next) { var account = await db.query(`query to check if account exists`).catch(next); if (accoun ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function is triggered which i ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

Leverage async/await within your React component

Do you think it's a good idea to directly use async/await in a React component and then store the result in the Redux store? Here's an example: class User extends Component { render() { return <div>{this.props.user.name}</d ...

Why is it that I am getting a promise when using React with Fetch and async/await?

I'm currently facing some issues with react, fetch, and async/await. Here is a snippet of code I have as a fetch wrapper: export const fetcher = (url, options = null) => { const handle401Response = error => { throw error; } const isRespo ...

Tips for speeding up the process of sending emails with nodemailer and firebase

We've successfully implemented code that triggers emails to a user and their contacts whenever a new node is added to a specific path in Firebase's realtime database. Currently, the average time taken to send these emails is approximately 4 minu ...

Using TypeScript with async await operators, promises, and the memoization pattern

I am currently in the process of updating my code to incorporate the latest TypeScript enhancements. We have implemented various memoization patterns, with the main goal being to ensure that services with multiple subscribers wait for one call and do not t ...

Vue.js Asynchronous while loop (continuously checking backend until task completion)

When working inside a vue action, I am interested in continuously checking the status of my backend by calling another async action until a certain task is completed (there will be a loader on the frontend to show progress). To elaborate, I need to keep m ...

Please display the Bootstrap Modal first before continuing

Currently, I'm facing a challenge with my JS code as it seems to continue running before displaying my Bootstrap Modal. On this website, users are required to input information and upon pressing the Save button, a function called "passTimeToSpring()" is e ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. Althou ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

Enhance your Shopify experience by utilizing the powerful functionality to manage your cart

I'm facing difficulties when adding or removing items from the cart attributes in Shopify. I've followed the guidance provided in the official documentation and essentially copied and made slight modifications to this code: let formData = { 'items': [{ ...

A versatile function in the NodeJS https module for sending requests and dynamically managing responses

This particular query resembles an older question on Stack Overflow, but unfortunately, the accepted solution didn't quite work for me. My setup involves utilizing the built-in 'https' module in NodeJS to interact with an external API. Specifically, I am ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { email_ad ...

Comparing JS Async/Await, Promise, and Callbacks: Which is Best

I'm trying to wrap my head around the differences between callbacks, promises, and async/await. While I understand how callbacks and promises work, I'm struggling with grasping the usage of async/await. I know it's essentially a syntactic sugar for promise ...

How can I manage asynchronous calls when querying Mongoose for each element in an array using Express?

Having trouble with the post method below because of a mongoose async issue. The code res.send(suggestions) is being executed before Expense.findOne.exec. app.post('/suggestions', async function(req, res) { const suggestions = await req.body.map((desc ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object then call ...

Strategies for ensuring that code does not execute in Angular until the API response has been received

Currently, I am facing an issue where I need to wait for data from an API in order to set the value of a variable and use it in an if condition. The problem lies in my uncertainty about how to properly handle this asynchronous task using async and await. ...

I am unable to transfer information retrieved from the fetch call to the express API

I'm facing a puzzling issue that has me stumped - I have code that should be working, but it's not. const getPhones = async () => { await fetch(url, requestOptions) .then((response) => response.text()) .then((XMLdata) => { const pa ...

Steps to resolve the error message "throw new Error(`If callbackSuccess is provided, callbackError must also be supplied`);"

My script to access the GeoTab API for retrieving vehicle data is encountering an issue. async function getFuelTypeDevices(){ fuelTypeDevices = await api.call("Get",{ "typeName":"Device", " ...

Nested Async await within a timer is failing to provide the expected result

Currently, I am working on testing the responses of endpoints using Mocha and Chai tests. Below you can find the code snippet for the same: async function fetchUserData (userId) { let response; let interval = setInterval(async () => { ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promises. Here ...

How can I prevent StateHasChanged() from affecting all open browsers in a Blazor Server-Side application?

Hey there, I'm new to Blazor but familiar with C#. This is my first time asking a question here so please bear with me. :) I am working on a Blazor server-side application where users can enter information and validate it based on server data. So far ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

Issue encountered - Attempting to provide an object as input parameter to puppeteer function was unsuccessful

Encountering an error when attempting to pass a simple object into an asynchronous function that utilizes puppeteer. The specific error message is: (node:4000) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: userInfo is not def ...

The curious case of Node.JS: The mysterious behaviour of await not waiting

I am currently utilizing a lambda function within AWS to perform certain tasks, and it is essential for the function to retrieve some data from the AWS SSM resource in order to carry out its operations effectively. However, I am encountering difficulties i ...

Asynchronous behavior in Node.js and MongoDB when using await for patch requests

After encountering an issue with syncing returns while using await, it became apparent that the problem lies within the response handling. While all the information successfully updates in MongoDB, the endpoint res.status(200).send(updatedData); ends up re ...

Include the await keyword within the .then block

I'm trying to execute an await after receiving a response in the .then callback of my code: const info = new getInfo(this.fetchDetails); info .retrieve() .then((res) => { const details = this.getLatestInfo(res, 'John'); }) .catch((error) =&g ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

Creating a comprehensive response involves merging two JSON responses from asynchronous API calls in a nodejs function block. Follow these steps to combine two REST API

New to JavaScript and the async/await methodology. I am working with two separate REST APIs that return JSON data. My goal is to call both APIs, combine their responses, and create a final JSON file. However, I am facing issues with updating my final varia ...

Struggling to resolve the unspecified outcome of an await operation

I'm looking to implement password comparison using the Bcrypt library. Here is the code snippet: bcrypt.js const bcrypt = require('bcrypt'); const saltRounds = 10; var Bcrypt = () => { } Bcrypt.encrypt = async function(password) { const hashedP ...

Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled. Problematic Code: const axios = require('axios'); co ...

What is the best way to manage a promise's response?

I'm currently facing a situation where I need to create a petition to an endpoint and retrieve the URL of the backend that I intend to use. My setup involves a file with the API configuration where I instantiate axios. Previously, my approach was simple a ...

Tips for ensuring a program pauses until an observable is completed within an Angular application

Currently, I am working on a project using Angular. I encountered a situation where a call to the backend is made using an observable to fetch products. Below is an example of how the code appears: getProducts () : Product[] { this.http.get<[]>(this ...

Avoid causing delays in the event loop by refraining from synchronous operations

My workplace currently operates a microservice that handles 300 requests per second across 30 NodeJS pods. DataDog metrics revealed high latency and CPU usage during peak request times. While monitoring the DataDog APM profiles for various pods, I noticed ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

When async/await is employed, the execution does not follow a specific order

I'm curious about the execution of async/await in JavaScript. Here are some example codes: async function firstMethod(){ new Promise((resolve, reject)) => { setTimeout(() => { resolve("test1"); }, 3000); }); } async funct ...

Mastering the proper implementation of observables, async/await, and subscribing in Angular

I have a JSON file located at assets/constants/props.json. Inside this file, there is a key called someValue with the value of abc. The structure of the JSON file can be seen in the following image: https://i.stack.imgur.com/MBOP4.jpg I also have a serv ...

What is the best way to retrieve JSON data in a React application?

useEffect(async () => { const fetchPostData = async () => { const response = await axios("") setPosts(response.data) } fetchPostData(); }, []) Rendering : posts.map(post => <li>{post.name} ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

Retrieving the initial data from a fetched JSON file in React

I'm struggling to extract the data from the initial object in a JSON document. const apiUrl = 'https://uniqueapi.com/data.json?limit=1'; function App() { const [items, setItems] = useState([]); useEffect(() => { async function fetchData() { ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

How can I efficiently fetch data from Firebase, manipulate it through computations, and present it using React Hooks?

I am currently working on retrieving multiple "game" objects from Firebase Storage, performing statistical calculations on them, and then presenting the game statistics in a table. Here is an overview of my code structure: function calculateTeamStatistics( ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

Managing Asynchronous Callbacks in JavaScript using Node.js

I am a beginner in the world of Javascript and I recently encountered a challenge with async callbacks using Node.js. My first step was setting up the Facebook webhook and sending a Webhook POST request Below is the code snippet : routes.js **Setting up ...

What is the best way to ensure that one method waits for another method to complete before proceeding?

Below is a React method that needs completion for uploading images to cloudinary and setting the URL in state before executing the API call addStudent. The order of execution seems correct at first glance, but the last API call crashes due to base64 data n ...

What is the best way to sequentially invoke an asynchronous function within an Observable method?

Presently, I have the following method: public classMethod( payload: Payload, ): Observable<Result> { const { targetProp } = payload; let target; return this.secondClass.secondClassMethod({ targetProp }).pipe( delayWhen(() ...

Node.js POST Request Batch Processing

For my request, I need to send a batch of 40 items with a 10-second break between each batch. After updating the parameters, when I run the following code: const request = require('request'); let options = { 'method': 'POST', 'url': 'https://mysite.com ...

Mastering the art of efficiently capturing syntax errors using coroutines in Python

Currently, I am in the process of developing a Python script that runs two tasks simultaneously. Transitioning from JavaScript to Python's async/await coroutine features has presented some challenges for me as I have encountered unexpected behavior. Initi ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

Establish a connection between Apollo and MongoDB

I'm struggling to connect my Apollo server with my mongoDB. Despite searching for examples, I can't seem to find a solution that addresses the async part of the process. It's surprising that there aren't more resources available. Am I missing something? I ...

Having trouble transmitting data with axios between React frontend and Node.js backend

My current challenge involves using axios to communicate with the back-end. The code structure seems to be causing an issue because when I attempt to access req.body in the back-end, it returns undefined. Here is a snippet of my front-end code: const respo ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged in down ...

Experience the quick sort programming algorithm in action using Vue.js without the hassle of dealing with Promises

I am currently experimenting with the quicksort algorithm visualization using Vue.js for self-educational purposes. However, I am facing some difficulties with async/await implementation. Although array filling and shuffling seem to work fine (although I a ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

I am having trouble getting the Express Router delete method to function properly when using mongoose with ES8 syntax

I was working on this code snippet : router.delete('/:id', (req, res) => { Input.findById(req.params.id) .then(Input => Input.remove().then(() => res.json({ success: true }))) .catch(err => res.status(404).json({ success: false })); ...

Is the callback not being triggered in the Stripe webhook? Or could I be overlooking something important?

I am currently working on a project using Next.js with Strapi and Stripe. The issue I am facing involves a webhook that is supposed to execute the markProductAsSold callback after a successful payment. However, this callback only runs correctly on localhos ...

Using async/await with Axios to send data in Vue.js results in different data being sent compared to using Postman

I am encountering an issue while trying to create data using Vue.js. The backend seems unable to read the data properly and just sends "undefined" to the database. However, when I try to create data using Postman, the backend is able to read the data witho ...

Executing asynchronous actions with useEffect

Within my useEffect hook, I am making several API requests: useEffect(() => { dispatch(action1()); dispatch(action2()); dispatch(action3()); }, []); I want to implement a 'loading' parameter using async/await functions in the hook. This par ...

What is the best way to wait for an asynchronous call within a __get__ method of a descriptor?

I am looking to implement a lazyloadable property that loads data when first accessed through __get__(). However, I cannot set __get__() as async. Is there a way to wait for obj.load() to finish and then return the getter's result? class LazyLoadableP ...

Is there a way to perform async-await operations one after the other?

I need to save the token in a cookie and then navigate to "/". In this "/" route, it requires the token value to be present in order to work properly. So, my plan is to use setCookie to store the token and then navigate once the token is available. I hav ...

What is the best way to transform these nested callback-heavy functions into async await or promises?

I'm relatively new to Node.js and I need to execute a series of functions one after the other, as they are interdependent. Initially, I opted for the callback function approach where I invoked another callback, essentially creating nested callbacks in ...

fetching all objects in one asynchronous request

Seeking assistance with this code on codesandbox. Can someone help? I am looking to display all the feeds from three different sites (stored in FEEDS) on a homepage without needing to click and navigate to a specific slug page. The issue I am facing is f ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

Implementing a progress loader in percentage by simultaneously running an asynchronous setTimeout counter alongside a Promise.all() operation

I'm encountering a problem running an asynchronous setTimeout counter simultaneously with a Promise.all() handler to display a progress loader in percentage. Here are the specifics: I've developed a Vue application comprised of three components. The fir ...

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code to function as ...

While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application. Here is the code: <template> ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...