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.

Receiving a 404 error consistently when using Await on findOne command

Every time I run the code below, it returns a not found (404) error. However, the data is being logged to the console as expected. My stack includes Node, Koa, and Mongoose. Here's the server.js: const Koa = require('koa'); const bodyparser = require('ko ...

Transmitting a Commitment as a Response in the HTTP protocol

I'm diving deeper into the world of promises in javascript. I grasp the fundamental syntax where promises are used by clients for handling asynchronous tasks like this: async function fetchMovies() { const response = await fetch('/movies'); // waits un ...

Performing an ASync call to the GetData routine in MongoClient using NodeJS

Combining code snippets from https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%20the%20async%20keyword%20before,a%20promise%20to%20be%20resolved. Upon ob ...

What is the best way to execute a SQL query within a JavaScript loop or map function?

I have a task at hand: Iterate through an array of objects using the map function Execute multiple SQL queries based on each object Append the query results to the respective objects The array I'm looping through contains offers, which are objects with a ...

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

"Utilizing asynchronous functions with Node.js to fetch and parse JSON

I seem to have encountered a minor issue. I am trying to send the value of postQuery.room in my res.json, but for some reason it is being sent as undefined. Can anyone help me understand why? GET ROUTE app.get('/', async function (req, res) { const pa ...

When the submit function is triggered, the Redux state may display either the previous value or the

Currently facing an issue with async await in my React project. It seems to not be properly awaiting a response as the Redux state is displaying the previous or default value when calling the function. Strangely enough, outside of the function everything s ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

Master the art of sending multiple asynchronous requests simultaneously with suspense in Vue 3

Utilizing <Suspense>, I am handling multiple requests in my child component using the await keyword: await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res); await store.dispatch("product/get ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

How do I ensure my Node.js code waits for a pipe and createWriteStream operation to complete before moving on to the next lines of

Recently delving into Nodejs, I encountered a challenge. I am in the midst of saving a zip file from an S3 bucket to an EC2 instance that hosts my Nodejs service. The next step involves decompressing the zip file locally within the file system on the EC2 s ...

What are some ways to delay the response time of my Express server in order to accommodate the functionality of the react-admin getOne() method?

I've implemented VetCreate and VetEdit functions to handle creating and editing records in my application. The issue I'm facing is that although the creation response is successful, the new record's ID is not populated when trying to fetch it. Even though ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...

What is the best way to anticipate the vue.js created hook?

I have a vue.js application where I am facing an issue with awaiting a call to the Prismic API. The call is initiated from the created hook, but I am unsure of how to make Vue await the hook itself. Here is an example of the code: ... async created() { ...

Is it necessary to include async/await in a method if there is already an await keyword where it is invoked?

Here are the two methods I have written in Typescript: async getCertURL(pol: string): Promise<string> { return await Api.getData(this.apiUrl + pol + this.certEndpoint, {timeout: 60000}).then( (response) => { return response.data.certUR ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

What is the reason for TestBed using waitForAsync in beforeEach instead of directly using async/await to compileComponents?

UPDATE: I submitted a problem report to Angular and they have since made changes to the documentation: https://github.com/angular/angular/issues/39740 When working on Angular tests, it is common practice to set up the beforeEach method like this: befo ...

Using Vue and Vuex to wait for asynchronous dispatch in the created hook

I'm struggling to implement asynchronous functionality for a function that retrieves data from Firebase: Upon component creation, I currently have the following: created(){ this.$store.dispatch("fetchSections"); } The Vuex action looks ...

"Why does the React useState array start off empty when the app loads, but then gets filled when I make edits to the code

I'm facing a challenging task of creating a React card grid with a filter. The data is fetched from an API I developed on MySQL AWS. Each card has a .tags property in JSON format, containing an array of tags associated with it. In App.jsx, I wrote Jav ...

The asynchronous nature of async await in Express Node.js is causing functions to execute non-sequ

I am having an issue with running 3 database queries and rendering the results to view using async/await in Node.js. It seems like the queries are not waiting and always sending null objects to the view before they finish executing. I'm not sure where ...

Node Express JS: Efficiently handling multiple fetch responses before sending data to client

My goal is to call an API that only accepts one animal name at a time, but I receive the names of multiple animals in a query separated by commas. To achieve this, I plan to call the API once for each animal, push the JSON data into an array, and then resp ...

Bring in an asynchronous function from another file to the component

Experiencing difficulties with learning NextJs, particularly async await for fetching data from Shopify. In my file library.js, all queries are stored: const domain = process.env.API_URL const storefrontAccessToken = process.env.ACCESS_TOKEN async funct ...

Display information using React upon successfully retrieving JSON data

I am using the load() function to fetch data: async function load() { let url = `www.com/file.json` let data = await (await fetch(url)).json() return data } Once I have my JSON file loaded from the server, I want to render my page: export cons ...

Efficient methods to reach the desired result using Selenium WebDriver promises

After working on a piece of code that utilizes Selenium WebDriver to retrieve the text of an element, I am wondering if there is a more concise way to accomplish this task? async function getText(driver, locator) { return await (await driver.findEleme ...

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').value; const feelin ...

Nuxt - Vue - Utilizing middleware on a layout in a few simple steps

Recently, I developed a middleware for authentication in my Nuxt application and now I want to utilize it within a layout. However, when trying to call the middleware using the following code: export default { middleware: 'auth', I encountered the fo ...

Storing the output of asynchronous promises in an array using async/await technique

I am currently working on a script to tally elements in a JSON file. However, I am encountering difficulty in saving the results of promises into an array. Below is the async function responsible for counting the elements: async function countItems(direct ...

Tips for synchronously waiting for a promise in a Node.js function

Using an asynchronous method, I generate a decrypted file that contains my users' credentials: initUsers(){ // decrypt user file var fs = require('fs'); var unzipper = require('unzipper'); unzipper.Open.file('encrypted.zip') ...

Is it possible for node.js to execute promises without needing to await their fulfillment?

When I visit the Discord tag, I enjoy solving questions that come my way. While I am quite proficient in Python, my skills in Javascript are just about average. However, I do try my hand at it from time to time. The Discord.py library consists of several ...

What specific mongoose query encounters issues when implementing async await?

I have a small requirement. I need to insert data into 2 different collections, Test1_Model and Test2_Model, which are Mongoose Models in Node.js. try { const test1 = new Test1_Model({ name: "Dummy" }); const saveTest1 = await test1.save(); ...

Using the Fetch API to set variables in Vue 2: Asynchronous Task

As someone who is new to working with async tasks, I'm having trouble understanding why my fetch API call isn't updating my Vue variable even though the data appears correctly in the console log. I've tried using Async/Await without success. ...

Leveraging async-await for carrying out a task following the deletion of a collection from a mongodb database

Trying to implement async await for executing an http request prior to running other code. Specifically, wanting to delete a collection in the mongodb database before proceeding with additional tasks. This is what has been attempted: app.component.ts: ...

Different ways to separate an axios call into a distinct method with vuex and typescript

I have been working on organizing my code in Vuex actions to improve readability and efficiency. Specifically, I want to extract the axios call into its own method, but I haven't been successful so far. Below is a snippet of my code: async updateProfile({ ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

What is the best way to get the latest props in the midst of an async function?

There's a fascinating open-source project called react-share, where the ShareButton component offers a prop known as beforeOnClick for customization. I've utilized this beforeOnClick to upload images to our CDN before sharing, ensuring that only shared ima ...

Encountering issues with Node-persist on a complex Node.js application leading to missing return

I've encountered an issue with my heavy node app where I'm using node-persist to save data locally. Specifically, in a certain step of the process, I have the following code: const localdb = require('node-persist') const storage = localdb.create({ttl: tru ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

What is it about the setTimeout function that allows it to not block other

Why is setTimeout considered non-blocking even though it is synchronous? And on which thread does it run if not the main thread? ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

The function _this2.setState does not work properly in asynchronous situations within React

I have an onChange handler that triggers a Promise Resolve function. This function fetches data array using "PromiseValue", and I use ".then( result )" to retrieve the array field. It works when I print "result" with console.log. However, the issue arises ...

What are the best practices for utilizing fetch() to retrieve data from a web API effectively?

Is there a way to store stock data in stockData and display it in the console upon form submission? Upon submitting the form, I only receive undefined. I suspect this may be due to a delay in fetching data from the API (but not certain). How can I resol ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Is there a way to exit from await Promise.all once any promise has been fulfilled in Chrome version 80?

Seeking the most efficient way to determine which server will respond to a request, I initially attempted sending requests in sequence. However, desiring to expedite this probing process, I revised my code as follows: async function probing(servers) { ...

Exploring the asynchronous nature of componentDidMount and triggering a re-render with force

I am puzzled by the behavior in the code provided. The async componentDidMount method seems to run forceUpdate only after waiting for the funcLazyLoad promise to be resolved. Typically, I would expect forceUpdate to wait for promise resolution only when wr ...

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 num ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Is it necessary to use asynchronous actions in Node.js only when developing server applications?

In the Node.js application I'm developing, there is a piece of code similar to this within an async function: await a(param1); await b(param2); await c(param3); await d(param4); From my understanding, this setup works well for a server-based app. Fo ...

JavaScript: function that operates asynchronously

I am new to JavaScript and encountered some issues with async functions. I have a function that fetches data from MongoDB by creating a promise, but it returns a collection with an empty object. async function getRating(item, applicant) { let arr = await ...

Terminate an asynchronous function

Currently, there is an express server running on Node.js where clients can create tasks that involve various processes such as cycles and database communication. The communication between the client and the server is facilitated through socket.io. I am lo ...

Ensuring Proper Execution with Node.js Callbacks

Just dipping my toes into nodejs. I'm looking to fetch my video list through the Vimeo API. Check it out here: Vimeo Developer API Guide In this code snippet, I'm hoping to receive either the body or an error from the callback function instead ...

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

Is it safe to remove the `async` keyword if there are no `await` statements in use

Forgive me if this is a silly question, but I'm considering removing the async function below since there are no await's. This code is part of a large production system, and I'm unsure if removing async could have unexpected consequences? (a ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

Express server controller encountering premature return from locally executed async function

I have developed an API endpoint using Node/Express. I am trying to call a local function asynchronously within the controller function, but instead of receiving the expected asynchronous results, the called local function is returning undefined immediat ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

The function error is currently in a waiting state as it already includes an

I encountered a particular issue that states: "await is only valid in async function." Here is the code snippet where the error occurs: async function solve(){ var requestUrl = "url"; $.ajax({url: "requestUrl", succes ...

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

When creating an async function, the type of return value must be the universal Promise<T> type

https://i.stack.imgur.com/MhNuX.png Can you explain why TSlint continues to show the error message "The return type of an async function or method must be the global Promise type"? I'm confused about what the issue might be. UPDATE: https://i.stack.img ...

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

What are some strategies for ensuring that the API call waits for the necessary data to be retrieved?

Currently, I am working with React Native and Redux. The initial state of Redux includes emailExists being set to null: const INITIAL_STATE = { // ... emailExists: null, }; During user registration, I first check if the user already exists by sending ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

Asynchronous and nested onSnapshot function in Firestore with await and async functionality

I'm facing an issue with the onSnapshot method. It seems to not await for the second onsnapshot call, resulting in an incorrect returned value. The users fetched in the second onsnapshot call are displayed later in the console log after the value has alrea ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encountering is ...

Facing challenges when running asynchronous mocha tests using async/await syntax

Working on E2E tests using mocha and selenium-webdriver has been quite a challenge for me. Although I have implemented async/await functions to handle most of the tests smoothly, I am facing an issue where none of the tests are completing successfully. Her ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have so far: async f ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

Retrieving information from the backend results in an endless cycle, preventing it from loading successfully

My lack of experience with Async functions is evident in the issue I'm facing. The code to fetch templates from a back-end into React keeps repeating without properly setting the state to the data. import React, { useState} from 'react'; imp ...

Issue with retrieving Vuex store in router.js using Async Await

I am encountering an issue while attempting to access the Vuex store in my router file. I am looking to define routes based on the data length stored in the Vuex state. Ideally, if the store's data is empty, I only require the Company List route to be di ...

The coloring feature in Excel Add-in's React component fails to populate cells after the "await" statement

Currently, I am developing a Microsoft Excel Add-in using React. My goal is to assign colors to specific cells based on the value in each cell, indicated by a color code (refer to the Board Color column in the image below). To achieve this, I retrieve the ...

Failed to store item in localStorage

After successfully setting an object to localStorage, the value of the object stays null. I suspect that my use of async/await is causing this issue. I can confirm that I am correctly setting the state, as when I log the user in and navigate to the index ...