w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
AngularJS REST async call not returning data
you have to return the promise in your service return $q.all(newsCall, tweetsCall).then(function(values) { var news = values[0].data.results; var tweets = values[1].data.results; var a = doSomeThing(news); var b = doSomeThingToo(tweets); return [a, b]; }); en then in your controller wait for it to resolve: dataService.getNewsAndTweets().then(function(data){ $scope.news = data[0]; $scope.tweets = data[0]; });

Categories : Rest

Apache CommonsExec async call preventing sync call
This is your callback: DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); This is your asynchronous executor: executor.execute(commandLine, resultHandler); But, in a asynchronous mode, right after calling executor.execute() the method will continue, but until something happens in another thread and resultHandler.onProcessComplete() or resultHandler.onProcessFailed() are called, you still don't know if the execution ended, and should not exit your runAsync() method. I believe changing your method to something like this will work: private static boolean runAsync(String command, String directory) { CommandLine commandLine = CommandLine.parse(command); System.out.println("Running async " + command); DefaultExecutor executor = getExecutor(directory)

Categories : Java

what is thread doing after returning from async point?
When your code hits an await expression (assuming the awaitable was not completed synchronously), control returns to the calling method, as if you had written return;. (it returns a Task<T> that the caller can use to await the completion of the async part) The calling method will then continue execution until it returns (it will usually return immediately as it too awaits the returned task), and so on until it reaches the top of the (user-facing portion of the) call stack. Once it hits the top of the call stack, that thread will do whatever it naturally does. If it's a UI thread, it will return to the message loop, keeping the UI responsive. If it's a ThreadPool thread (or an ASP.Net worker thread), it will return to the pool and wait (synchronously) for more work. If it's a "ra

Categories : C#

Returning a String in an Async Event Handler
Simply fire an event to notify "outside world" about completion of operation. For this define your delegate: public void delegate OnError(object sender, string message); public event OnError OnErrorEvent; ... client.DownloadStringCompleted += (senders, ex) => { if (ex.Error == null) { //Process the result... return ex.Result; } else { if(OnErrorEvent != null) OnErrorEvent(this, "An error occurred. The details of the error: " + ex.Error;); } }; This is just an example, you have to choose more approriate signature of delegate for your concrete case.

Categories : C#

AWAIT / ASYNC example of background worker returning List
The reason you haven't seen examples of using async with synchronous code is because async is for asynchronous code. That said, you can use Task.Run as an approximate replacement for BackgroundWorker. Task.Run enables you to take synchronous code and consume it in an asynchronous way: main() { List<string> resultSet = await Task.Run(() => CreateList(dirPath)); console.out(resultSet.ToString()); } public List<string> CreateList(string dirPath); { //do some work on dirPath NOT CALLING ANY ASYNC methods return LIST<STRING>; } I'm currently going through a series on my blog on replacing BackgroundWorker with Task.Run, which you may find helpful.

Categories : C#

Async Await MVC Action returning Task instead of ActionResult
The ErrorHandlingControllerFactory from ELMAH returns a custom action invoker which it uses to make sure its HandleErrorWithElmahAttribute is applied to the controller. It never supplies an async action invoker so it doesn't understand async/await. Two workarounds; Try upgrading to the latest ELMAH - it may have fixes for async/await. Remove the call to ControllerBuilder.Current.SetControllerFactory(new ErrorHandlingControllerFactory()) and simply add HandleErrorWithElmahAttribute to the global filters using GlobalFilters.Filters.Add(new HandleErrorWithElmahAttribute()); Cheers, Dean

Categories : Asp Net Mvc

error in returning result in doInBackGround() in Async task
You can not write this line in background thread xx.setText(EntityUtils.toString(response.getEntity())); because you cant update UI from non ui thread. so write this line in onPostExecute() method.

Categories : Android

Async method returning Task with generic constraint in C#
Although I am not sure this is the best solution (or feasible in your specific use case), what you can do is: public class Response { public bool Success { get; private set; } public ExceptionDispatchInfo ErrorInfo { get; private set; } public bool HasFailed { get { return !Success; } } public static T CreateErrorResponse<T>(ExceptionDispatchInfo errorInfo) where T : Response, new() { var response = new T(); response.Success = false; response.ErrorInfo = errorInfo; return response; } } Usage: catch (HttpRequestException hex) { return Response.CreateErrorResponse<T>(ExceptionDispatchInfo.Capture(hex)); // should compile (I did not check) }

Categories : C#

Spring MVC test framework returning inconsistent results for async controller tests
You need to call asyncStarted MvcResult mvcResult = this.mockMvc.perform(get(this.basePath) .accept(MediaType.APPLICATION_JSON)).andExpect(request().asyncStarted()) .andReturn(); Though this still gave inconsistent results at times for me

Categories : Java

Async call in MVC 4
I think using Task is a better approach here: if(saveStatus){ new Task(AuditService.Add("Employee {0} added successfully", e.Name)).Start(); } Update: As Stephen pointed out in his answer, this may cause your in-progress work to be lost.

Categories : C#

GWT Async call always fail
When generating the code for your client-side service-async stub, it takes the value of the @RemoteServiceRelativePath annotation and prefixes it with the GWT.getModuleBaseURL() (this is explained in the javadoc for RemoteServiceRelativePath). GWT.getModuleBaseURL() is the "folder" where your nocache.js file is located. In a standard setup, this depends directly on the name of your module (project.gwt.xml and the package you put it in) or a rename-to argument you have in it. According to the error message, it's http://…/project/ in your case (your nocache.js is at project/project.nocache.js). You have to adjust the <url-pattern> in your web.xml file to match that URL, so it should be /project/employeeService in your case. Put simply: with @RemoteServiceRelativePath you configure

Categories : Java

Return a value from a async method call in WP8 C#
In your class XMLHttpRequestHandler create an Action: class XMLHttpRequestHandler { public Action<string> CallbackComplete; } And in your method GetResponseCallback you invoke that action if it's set. if(CallbackComplete != null){CallbackComplete(vResponse);} In your caller class you set up a method that is called when this happens(you get your response): private void OnObCallbackComplete(string str) { //Do stuff } ob.CallbackComplete = OnObCallbackComplete;

Categories : C#

IOS - Update progress bar from a async call
Switch back to the main thread before calling updateProgressBar. You can use GCD or performSelector to do so. [self.delegate performSelectorOnMainThread:@selector(updateProgressBar) withObject:nil waitUntilDone:NO];

Categories : IOS

Call async method without await
The compiler warning is there because it's almost always a mistake to do this. For one thing, you don't get any kind of notification that the task completed, and you also don't get notified of errors. To avoid the compiler warning, you can just assign it to an unused local variable, like this: var _ = Config.StorageCacheImpl.SaveAsync... In your case, I'd also recommend using a helper method instead of ContinueWith to make the code a little cleaner: private static async Task SaveAsync(string imageUrl, Stream resultStream) { bool success = false; try { success = await Config.StorageCacheImpl.SaveAsync(imageUrl, downloadResult.ResultStream); } finally { if (!success) Log("[error] failed to save in storage: " + imageUri); } }

Categories : C#

How is async w/ await different from a synchronous call?
Calling await client.GetStringAsync() yields the execution to the calling method, which means it won't wait for the method to finish executing, and thus won't block the thread. Once it's done executing in the background, the method will continue from where it stopped. If you just call client.GetString(), the thread's execution won't continue until this method finished executing, which will block the thread and may cause the UI to become unresponsive. Example: public void MainFunc() { InnerFunc(); Console.WriteLine("InnerFunc finished"); } public void InnerFunc() { // This causes InnerFunc to return execution to MainFunc, // which will display "InnerFunc finished" immediately. string urlContents = await client.GetStringAsync(); // Do stuff with urlContents } pu

Categories : C#

should you create new Async Tasks for every different call or use the same one
It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async. Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.

Categories : Android

angularJS data not available due to async call
I think you want to look at resolve: http://www.youtube.com/watch?v=Kr1qZ8Ik9G8 This allows you to load all your data before instantiating your controller and firing a routeChangeSuccess event. In the angular docs.

Categories : Javascript

How to call async task by using .ContinueWith
What makes you think you need ContinueWith? The appropriate replacement for Result is await. As a side note, you should end async methods with "Async": public async static Task<Bitmap> RollUpDrawingsImage(IElevation elevation) { int height = 0, width = 800; Bitmap completeDrawings = null; using (Bitmap elevationDoor = await ShopDrawing.Merger.MergeElevationAndDoorAsync(elevation, RotateFlipType.Rotate90FlipNone)) using (Bitmap partsList = await (await MaterialsList.Manager.GetMaterialListAsync(elevation)).GetDrawingAsync()) using (Bitmap optimized = await (await Optimization.Manager.GetOptimizedPartsAsync(elevation)).GetDrawingAsync()) using (Bitmap cutSheet = await (await CutSheet.Manager.GetCutSheetAsync(elevation)).GetDrawingAsync()) { height = (elevationDoor.

Categories : C#

WCF async call runs synchronously instead
This is an overview of the steps to achieve WFC async calls Declare two relevant method: one as BeginMethodName and another as EndMethodName. Add [OperationContract(AsyncPattern = true)] to the relevant Begin method. Do not provide the OperationContract attribute to the corresponding End method. In the service implementation, the actual processing should go in a method, and this method should run on a separate thread, to achieve this you can use ThreadPool.QueueUserWorkItem. On the client side, call the relevant Begin method, but do not close the proxy after this because the End method needs the same channel to get the result. You can close it in the client's callback after calling the End method. All the details to achieve WCF asyn calls are here here http://www.codeproject.com/Artic

Categories : C#

web client call server, server call 3rd party, all async?
It doesn't look like the server-side code needs to call the external service asynchronously. I'm not seeing an advantage in doing that. The client-side code would call the server-side code asynchronously, of course. (An AJAX request, using jQuery for example.) And it would await the response form that service in an asynchronous manner before handling that response. But since the server-side code in this request is only serving that one request, it can do so synchronously. Indeed, if the server-side code were itself also asynchronous then it would return control to the client-side code immediately before it has anything useful to give it. Which means the client-side asynchronous handler can't do anything. Instead, when the server-side code gets a response from the external service,

Categories : Web Services

Differences between Async CTP and Bcl.Async when calling async methods as sync
As a general rule, synchronous wrappers around asynchronous methods are strongly discouraged. When you use the Result approach, you run the risk of deadlock (as I describe on my blog); also, Result will wrap any exceptions, which makes your error handling much trickier. So I'd say "don't do that." As far as the Async CTP goes, there are a number of bugs that are known to exist (plus several more that are not public). And they're not going to be fixed. I strongly recommend upgrading everyone to VS2012. For this particular issue, it may be performance-related. E.g., Task.Delay(1) returns a task that will complete almost immediately, so there's a race condition between starting the delay and the await which checks whether the task is already complete. So it's possible that performance impr

Categories : Misc

Execute ajax only after previous async call
i tried on this first time so might be wrong, or maybe not the result you want, hope it helps: function firstAsyncCall(el){ return $.get( "/echo/json/" ).done(function(){ $("#"+el).css("background", "red"); }); } function secondAsyncCall(){ return $.get( "/echo/json/" ).done(function(){ $("div").css("border", "2px solid blue"); }); } var a = function(){ var that = this; var ajaxReq = []; var datas = ["data1", "data2", "data3"]; var dfd = new $.Deferred(); $.each(datas, function(i,el){ ajaxReq.push(firstAsyncCall(el)); }); ajaxReq.push(secondAsyncCall()); $.when.apply($, ajaxReq).then(function(){ dfd.resolve(); }); return dfd.promise() } var b = function() { var myA = a(); myA.done( functi

Categories : Jquery

How do I call async methods in lambda expression?
Not very clear from your question what exactly you want. This may help you, it will first calculate all the values and then will sort it with it, although your term aync is unclear to me for this context. MyList.Select(p=>new {p,CalcValue = CalcValue(p)}) .OrderBy(x=>x.CalcValue) .Select(x=>x.p);

Categories : C#

MVVMLight command CanExecute not firing after async call
I have the same problem, i was able to correct it two different ways, not sure which is "best". 1) Inside my Task , i put: App.Current.Dispatcher.BeginInvoke((Action)delegate() { yourCommand.RaiseCanExecuteChanged(); }); I didn't really like the idea of having to call RaiseCanExecuteChanged in multiple places, so i ended up using this: 2) i. I added to the Constructor: this.PropertyChanged+=my_PropertyChanged; ii. private void me_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "whateverPropertyNamethatcontrolsit": ((RelayCommand)FirstCommand).RaiseCanExecuteChanged(); break;

Categories : C#

how to update a bunch of entities with one async call(submit)
In this case I would use an invoke operation on the service. That way you simply invoke the method and there is no need to previously load any entity to the client. To do so first create an invoke operation on your service [EnableClientAccess] public class MyDomainService : DomainService { [Invoke(HasSideEffects = true)] public void UpdateCol3OfAllEntities() { // Use you data access layer to perform the neccessary // query: "UPDATE MyTab SET col3 = 'X'"... } } You can even extend the method by passing the ids to it: [Invoke(HasSideEffects = true)] public void UpdateCol3OfAllEntitiesWithIds(int[] ids) { // Use you data access layer to perform the neccessary // query: "UPDATE MyTab SET col3 = 'X' WHERE id IN (...)"... } Then simply invoke that

Categories : C#

How to make the return call wait for async complete c#
If you need to block the thread until an async operation is completed, you can use ManualResetEvent, like this: ManualResetEvent wait = new ManualResetEvent(false); wc.DownloadStringCompleted += (s,e) => { // ... // allow to proceed wait.Set(); }; // wait until Set wait.WaitOne(); return parseWebReturn(rawWebReturn,ret); In general though, you don't want to block threads, but rather use callbacks. You can do that by providing an Action delegate instead of the return value: public static void Login(String username, String password, Action<dbObj> callback) { // ... wc.DownloadStringCompleted += (s,e) => { if(e.Error!=null)

Categories : C#

View displaying on top of loading icon due to async call
It's hard to gauge without seeing your table view delegate/datasource methods, but your intuition makes sense. In this case, I can see two options: Add some logic to your delegate/datasource methods to properly show your loading view if the table is empty. Rather than add the loading view to the table view, add the loading view to the table view's superview. That way, you can ensure that the loading view is always on top of the table view. I usually opt for the second method, because I prefer to focus my datasource and delegate methods on only the table view. Hope this helps!

Categories : IOS

qunit + mockjax: When should I call mockjaxClear in async tests?
If you take a look at the code, you will see that the cleanup does not affect already "running" calls. It just makes sure that any subsequent $.ajax() will call jQuery's original method and that other internal state (but again, not affecting already pending "requests") is cleaned. This may help to ensure that the $.ajax() call under test test is only sent once (if more are sent they will fail, moreover the start() method will be called again, reporting the error to Qunit). It could also be this way just to keep code clean (less stuff in the callback handlers).

Categories : Javascript

Spring 3: How to call @Async annotated methods from the TaskExecutor
Here's an example of @Async use: @Async void doSomething() { // this will be executed asynchronously } Now call that method from another class and it will run asynchronously. If you want a return value use a Future @Async Future<String> returnSomething(int i) { // this will be executed asynchronously } The relationship between @Async and TaskExecutor is that @Async uses a TaskExecutor behind the scenes. From the docs: By default when specifying @Async on a method, the executor that will be used is the one supplied to the 'annotation-driven' element as described above. However, the value attribute of the @Async annotation can be used when needing to indicate that an executor other than the default should be used when executing a given method. So to set up a default

Categories : Java

Play Framework WS async call is repeated after an HTTP 401
This turns out to be an issue with the Async Http Client, a dependency of the Play Framework. It's fixed in com.ning:async-http-client:1.7.12 - https://github.com/AsyncHttpClient/async-http-client/issues/213 To update the dependency modify your project/Build.scala as follows: ... val appDependencies = Seq( .... "com.ning" % "async-http-client" % "1.7.17" )

Categories : Java

How to create async call with jquery with android using phonegap?
Your $.ajax code looks right to me, so it shouldn't block the app behavior. I don't completely understand your question... user shoudn't be allowed to do anything until the localstorage.setitem is set? If this is right, you could use jquery to enable some kind of "NEXT" button after the setItem instruction, so the user won't be able to move on until the async call is done.

Categories : Android

AngularJS Bind Data returned from Async Call in ngrepeat
This worked for me: Binding variables from Service/Factory to Controllers Also watching the videos at egghead.io helped a ton (http://www.egghead.io/lessons)

Categories : Angularjs

Node.js - howto block around async call. Or non-blocking xmltojs lib
you can ask xml2json to return object: var json = parser.toJson(body, {object: true}); if you decide to use async parser then just put your done callback inside json result handler. There is no need to "block" async function: var parseString = require('xml2js').parseString; parseString(body, function(err, json) { // handle error: return done(err) // do your logic if no error // ... // profile._json = json; // ... // // 'return' result done(null, profile); });

Categories : Javascript

In nodejs, is there a better design pattern to call async functions synchronously?
For your second example I recommend using events. If you use registered events, along with a global(or closure) counter, it will keep the call stack from growing, but achieve the same logic. Assume the countDown method does some asynchronous work, just pass this async work a callback that emits the next event in line. var events = require("events"); function recursiveCountDown(someVariable) { var counter = someVariable; var eventEmitter = new events.EventEmitter();//create a new event object, so we can have lots of these running potentially without interfering with one another! var eventName = 'count'; function countDown() { someVariable--; console.log(someVariable); if(someVariable) eventEmitter.emit(eventName); } eventEmitter.on(event

Categories : Javascript

Wait for handle/event async or call back within the same thread
Here - http://pastebin.com/ucpDdYGZ - is my decision of a problem. Sorry for non-english comments (they are in russian). The main idea is to create a dummy window with m_wnd = CreateWindowA( "STATIC", "", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_MESSAGE, NULL, NULL, NULL); and to send it a message via SendMessage

Categories : C++

Playframework scala, how to asynchronous convert a web service call to a response without Async
If you look at http://www.playframework.com/documentation/2.1.3/ScalaAsync you are told to use the Async method. When you look at the signature you will see how the magic works: def Async(promise : scala.concurrent.Future[play.api.mvc.Result]) : play.api.mvc.AsyncResult The method returns AsyncResult, which is a subclass of Result. That means we need to do our work of generating our normal Result within a Future. We can then pass the future result to this method, return it in our action method, and Play will take care of the rest. def Authenticated[A](p: BodyParser[A])(f: AuthenticatedRequest[A] => Result) = { request => { case class UserPair(userId: String, user: User) val userPair: Option[UserPair] = for { userId <- request.session.get(use

Categories : Scala

Async JavaScript Function on Client Side( how to write call back)
You wont have access to the DOM Parser in a WebWorker, so this method is not applicable. You will need to run portions of the code on a timer event. Here is a library that may be able to help with running code against a timer -> https://github.com/jameswestgate/taskjs

Categories : Javascript

angular - controllers .then function called after directive so no data avail async call
Try using the success and error methods of the returned $http object if you're just trying to set a value. These methods are specific to the objects returned by $http. $http.get('data/data.json') .success(function(data, status, headers, config){ $scope.result = data; }) .error(function(data, status, headers, config){ console.log(data); )}; Any errors that you're getting could also be helpful. Also you probably don't want to couple your directive so tightly with your controller by referencing $scope.result. You may want to just pass in the data to render as an attribute, in which case egghead.io has some great tutorials on the subject (directive isolate scope).

Categories : Javascript

How to call another module without returning to the first one after completion?
I think all you're looking for is the command Exit Sub which will make the program leave the subroutine without continuing any further, But the way you usually want to do this is, rather than calling a Sub, rather call a Function that returns a boolean value. So, for example: Public Function MyFunc() as Boolean .... If [good] MyFunc = True Else MyFunc = False End Function Then you could do something along the lines of: Sub MyCallingSub() ... If MyFunc = True then Exit Sub Else ... End Sub It just adds in A LOT more felxibility and ability to choose whether you want to continue further in your sub or not. Hope that makes sense.

Categories : Excel

Returning many columns in a function call
Update: After second look I see that you're using a function(completely overlooked) which returns only one value , can you change it to procedure instead? SQL: DROP PROCEDURE IF EXISTS procedure_institute_university; DELIMITER $$ CREATE PROCEDURE procedure_institute_university (IN_partnership_id INTEGER(11)) BEGIN SELECT UPPER(institute.Code) as `institiute_code`, university.id as `university_id`, UPPER(university.UnivAcronym) as `university_acronym` FROM partnership LEFT JOIN institute ON institute.id = partnership.iid LEFT JOIN university ON university.id = partnership.uid WHERE partnership.id = IN_partnership_id AND partnership.active = '1' LIMIT 1; END$$ PHP: $sql = "call procedure_institute_university(15)"; $ru

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.