Questions tagged [async-await]

1

votes
1

answer
2.2k

Views

Problems with async code in Jest tests

I am having problem with getting the code into the beforeAll function finish and wait for the promise that resolves the storyLinks. The console log at the end of the snippet returns undefined but I need it to return the hrefs of the stories in my storybook. I cannot wrap this into an async function...
Ruxandra Anghel
1

votes
1

answer
1.9k

Views

NodeJS, get return value from async await

I have an async await function that uses mongoose: const createModelB = async (id) => { try { let user = await User.findOne({id: id}); if (user) { let modelB = new ModelB({ user_id: user.id }); modelB = await scrum.save(); return modelB; } return null; } catch (err) { console.error(err); } return nu...
Mr.D
1

votes
2

answer
879

Views

Ajax and async await

I am a bit confused as to why my ajax call doesnt return a result. I thought a method defined as async automatically returns a promise. What am I doing wrong? async AjaxCall(filePath) { let xhttp = new XMLHttpRequest(); xhttp.open('POST', filePath, true); xhttp.setRequestHeader('Content-type', 'appl...
Asperger
1

votes
2

answer
341

Views

Node.js await catch not returning

I am busy working with some code that is responing in an unexpected way (to me). It involves handling Node.js promise exceptions. I have the following function modified so that all it does is fail function asynFunc() { return new Promise(function(res, rej) { rej('GENERIC ERROR'); }); } The problem c...
TheLovelySausage
0

votes
0

answer
6

Views

Nodejs - Await does not waits for the method to execute first

I am writing a function in nodejs to send print command to the macos. The problem is that my print command is sent successfully but I want to wait for the output received before moving forward. My code is as follows const printer = require('node-native-printer'); const exec = require('child_process'...
VIBHOR GOYAL
1

votes
1

answer
32

Views

How to async long process from button [duplicate]

This question already has an answer here: How and when to use ‘async’ and ‘await’ 21 answers Currently I have a button that calls a function and has a processing time of 10-20 secs. Is it possible to have some text like 'please wait...' rather than the application getting hang. Here is butt...
Rock n' Roll
1

votes
2

answer
134

Views

How to iterate async function in puppeteer with NodeJS

I want to take a screenshot with puppeteer and it's working for one post. But I want to make it iterate. If it's normal function I can just wrote the function name in the last side of the code so that it can iterate. But this is async function so I don't know how to iterate it. const puppeteer = req...
sangumee
1

votes
4

answer
84

Views

How can I make tasks wait for the same result?

I have a simple singleton class, public class SimpleSingleton { public async Task GetRefreshedValue() { /* What goes here? */ return await GetRefreshedValueImplementation(); /* What goes here? */ } private async Task GetRefreshedValueImplementation() { /* Resource intensive and not thread safe */ }...
Jodrell
1

votes
3

answer
57

Views

Handling async exceptions

I'm wondering how I can let this code fall in the catch of PassThrough? using System; using System.Threading.Tasks; public class Program { public static async Task Main(string[] args) { try { await PassThrough(Test()); } catch (Exception) { Console.WriteLine('caught at invocation'); } Console.ReadLi...
grmbl
1

votes
1

answer
54

Views

How to consume this EF Core C# async method in F#?

I am using F# with Entity Framework and I can't get my head around consuming C# async methods from F#. Despite others SO answers related to similar issues can't really get my head around. Here is my attempt with the code below, initially synchronous: let getAirport (id: Guid) = use context = new MyC...
Ehouarn Perret
1

votes
3

answer
58

Views

How to await a fetch function in a function?

Below is my code export const redirectDomain: any = (lang, ctx, res) => { let redirectString; const getData = async () => { try { const response = await fetch('https://www.example.com'); const data= await response.json(); return data; } catch (error) { console.log('[ERROR]'); } }; const data = getD...
Dreams
1

votes
2

answer
34

Views

Why does my do..while loop not execute the setTimeout within the async-await code correctly?

I have a do..while loop that executes a promise and awaits the response. The loop needs to continue while the response is either 'Processing' or 'Received'. However, there is a setTimeout function within the Promise. The goal here is that the function, respo = await promise1.then(resp => resp),...
Stephan Du Toit
1

votes
4

answer
61

Views

Why do I get a warning when trying to run an async method on another thread?

I have an async method, which calls another async method, however, I want it run on a separate thread in parallel: public async Task ServePage() { Task.Run(() => DoThings(10)); // warning here // ... other code return new Page(); } public async Task DoThings(int foo) { // stuff } The warning state...
AngryHacker
0

votes
0

answer
23

Views

How can I maintain a chaining of results approach while performing a non-blocking wait?

Background: I use a Result class that lets me chain success and failure lambdas together. For example: var result = DoSomething(); result.OnSuccess(() => DoSomethingElse()).OnFailure(() => LogFailure()); One of the OnSuccess functions I have is: public Result OnSuccess(Func func) { if (!this.Success...
Craig
0

votes
0

answer
34

Views

Async/Await: Value does not fall within the expected range

Getting the following error in my ASP.NET application 'Value does not fall within the expected range' with stack trace: System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) at System.Web.Hosting.IIS7WorkerRequest.GetUserToken() at System.Web.HttpConte...
Raghav
-1

votes
0

answer
23

Views

Why does this function never run even if it did before?

I'm using React.js & Web3.js to create a dapp. I believe this question is more related to react.js and javascript and that's why I'm not posting in in Ethereum Stackexchange. Consider the following code: allowAddress = async() => { let approvedAddress = this.state.approvedAddress; let approvedValue...
Sophie259
1

votes
1

answer
601

Views

Mapper.Map<Task<IEnumerable<Address>>, Task<IEnumerable<AddressView>>()

.NET Framework 4.5.2, .Asp.NET Web API 5.2.3, AutoMapper 5.1.1 I have the following ASP.NET MVC WebApi Action Method on the AddressController. For my test I return only 10 records as you can see in service method below: [Route('api/Address/GetAllAsync')] [HttpGet] public async Task GetAllAsync() { A...
user1798599
1

votes
3

answer
746

Views

Alternative to using async () => in Rx Finally

My understanding is that async void, should be avoided and that async () => is just async void in disguise when used with Action. Hence, using the Rx.NET Finally operator asynchronously with async () => should be avoided since Finally accepts Action as parameter: IObservable.Finally(async () => { a...
Jasper H Bojsen
1

votes
1

answer
476

Views

Create Task without lambda

Trying to pass function instead lambda expression and finally mixed up why line: int t2 = await Task.Run( ()=>Allocate2() ); not raises error. This lambda expression ()=>Allocate2() not returns Task. Why no error? How to create task without lambda expression with function Allocate? static async void...
vico
1

votes
3

answer
330

Views

Exporting and requiring an async function error

I export an async function in a file called resourcess.js like this: //resourcess.js module.exports = function(arg) { let do_stuff = async (arg) => { ... } Then i require that file in routes.js like this: let importedFunc = require('./resourcess.js'); Finally i use it in routes.js like this: app.pos...
user1584421
1

votes
1

answer
69

Views

Async/await with a task, refactoring method

In the below .net code is the async/await needed when there is also a task in the method? transaction.execute returns a string which is then returned by the method. This is a slow running method. I know async/await runs on the main thread using a state machine and that the task will run on a threadp...
Ben Cameron
1

votes
2

answer
91

Views

Calling a synchronous method in an async fashion?

I'm developing an ASP.NET MVC WebApi project and one of the methods needs to make a LDAP search. The amount of information the search retrieves from the LDAP server ensures the call takes at least 7 seconds to complete. The call, as it uses the System.DirectoryServices.Protocols classes and methods,...
Léster
1

votes
3

answer
75

Views

How to call function at fixed interval with ensuring previous function is completed

I have a Promise based function which i want to call at fixed interval, Lets say at every 60 seconds. But i also want to make sure that function is called only if the previously called function is executed completely and i want to continue this for infinite time function fun(){ return new Promise((r...
Krunal Sonparate
1

votes
2

answer
93

Views

Correct way to use async/await in an Angular and Ionic app

I have an Ionic app where on one of the page I am inserting some records in SQLite DB after the user fills out a form. In order to make sure that the user navigates to the next page only after the data gets inserted in DB I am using async/await feature. What I am not sure though is if I am using th...
user2325154
1

votes
3

answer
83

Views

How to put async method in a list and invoke them iteratively?

Recently I want to implement a health check for a list of service calls. They are all async task (e.g. Task method_name(...) I would like to put all of them into a list. I followed the answer of this post: Storing a list of methods in C# However, they are async methods. I put it like this: a collec...
Terence
1

votes
1

answer
38

Views

Async await one of many

Is there a way to perform an async await on a group of promises, but only await the first completion? For example: async function run() { const ms = Math.floor(Math.random() * 1000); return new Promise(resolve => setTimeout(resolve, ms)); } async function test() { await Promise.first([run(), run(),...
insou
1

votes
3

answer
69

Views

How to reduce frequency of continuously fired event's event handling

I am learning about tasks and async/await in c#. So please consider the stupidity of my question. There is an event DummyEvent in a class. An event handler DummyEventHandler is subscribed to this event and it handles a large amount of CPU bound task, which is actually not needed to be used so freque...
Muzib
1

votes
1

answer
92

Views

bottleneck running task.run on asp net mvc

I have doubts regarding The legacy ASP.NET Synchronization-Context, If I run the following methods in an ASP.Net MVC Application: `Task.Run(async () => await httpClient.getContentAsync()).Result var response= Task.Run(() => methodAsync(model)); var other = response.Result var response= await Tas...
developer
1

votes
1

answer
43

Views

Data Access with Async and Sync needs

Is there a best practice for a design for a data access layer that could have both a need for Async and Non-Async calls? I've seen some other posts that seem to be saying that using Task.Run on async calls is a 'work-around' to calling async methods synchronously. Example of a method I have (service...
Voss Grose
1

votes
1

answer
84

Views

Async / await vs then which is the best for performance?

I have a simple code in JavaScript that execute a request in an API and return the response, simple. But in this case I will have thousands of requests. So, which one of the code options will perform better, and why. Also which one is recommended as good pratices these days? First options is using...
Francisco
1

votes
1

answer
66

Views

Choosing not to await async function in action in ASP.NET Core WebAPI controller

The scenario is the following: Backend: Asp.NET Core WebAPI 2.2 Frontend: iOS and Android which consumes the API I have a function allowing the user to send messages to other users. The sending of a message is done in an asynchronous action: public async Task CreateMessage This action does the foll...
solojuve1897
1

votes
1

answer
45

Views

Can await and then be mixed in one implementation?

I'm wondering if await and .then can be used in the same async function? Here is my function: uploadImageToImgur: async function (file) { return new Promise(function(resolve, reject) { const url = 'https://api.imgur.com/3/image', reader = new FileReader(); if (file) { reader.readAsDataURL(file); }...
JKowalski
1

votes
2

answer
76

Views

async file reading 40 times slower than synchronous or manual Threads

I have 3 files, each 1 million rows long and I'm reading them line by line. No processing, just reading as I'm just trialling things out. If I do this synchronously it takes 1 second. If I switch to using Threads, one for each file, it is slightly quicker (code not below, but I simply created a new...
Neil Walker
1

votes
1

answer
59

Views

return await Task.FromResult or suppress warning? [duplicate]

This question already has an answer here: Await or Task.FromResult 2 answers We have a legacy method with return type of async Task. Its current implementation needs to query the database thus the need for asynchronous operation. But we're changing it to just use in-memory objects so basically we d...
Paolo Go
1

votes
1

answer
41

Views

How to avoid “uncaught error in promise” with async/await

The following code is an MCVE of my problem: class MyApp { public async crash(): Promise { throw new Error('Hello Error'); } public async chain(promise: Promise) { await this.delay(10000); return promise; } private async delay(ms: number): Promise { return new Promise( resolve => setTimeout(resolve...
nvoigt
1

votes
2

answer
77

Views

Correctly implementing Tasks in a WPF application

I'm looking for some advice on getting to grips with Tasks in WPF and was wondering if anyone could have a look over my code and point out what I'm doing incorrectly? Basically the application takes a postcode from the UI which is used to instantiate a Task service which will get Longitude/Latitude...
Luke Dee
1

votes
2

answer
76

Views

Using async/await to find the value of a cors request?

I'm attempting to execute a CORS request, then use async/await to get value out of it (I'm using jquery btw). The functions createCORSRequest and executeCORSRequest both work fine I believe, so the implementation doesn't really matter. The function getDailyGames uses await to receive a promise crea...
16jacobj
1

votes
4

answer
49

Views

How to convert Tuple to Async Task

I'm doing a small application and I need help, because I do not know where the problem is. I have not been with C # for a long time and I am learning little by little, because all this is leisure form me, no more. I have the following Tuple that is working correctly: private Tuple CheckStatus() { in...
Mendizalea
1

votes
2

answer
61

Views

Modify object in for loop (async/await)

exports.allUsers = async (req, res, next) => { try { let users = await User.find({}) console.log(users) // [{ role: 'user', // skills: [...], // email: '[email protected]', // education: [], // createdAt: 2019-04-02T11:17:33.979Z // }, // { role: 'admin', // skills: [...], // email: 'f...
mrks
1

votes
2

answer
57

Views

Kotlin: Any performance impact on converting a “normal” function to a blocking suspend function?

I have a function that looks like this: fun map(block: (T) -> R): Result { ... } and I'd like to make a suspending version: suspend fun mapAsync(block: suspend (T) -> R): Result { ... } The logic in both bodies are identical, but one suspends and one doesn't. I don't want to have this duplicated l...
Matt Klein

View additional questions