Search Results

Search found 184 results on 8 pages for 'promises'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • Metro: Promises

    - by Stephen.Walther
    The goal of this blog entry is to describe the Promise class in the WinJS library. You can use promises whenever you need to perform an asynchronous operation such as retrieving data from a remote website or a file from the file system. Promises are used extensively in the WinJS library. Asynchronous Programming Some code executes immediately, some code requires time to complete or might never complete at all. For example, retrieving the value of a local variable is an immediate operation. Retrieving data from a remote website takes longer or might not complete at all. When an operation might take a long time to complete, you should write your code so that it executes asynchronously. Instead of waiting for an operation to complete, you should start the operation and then do something else until you receive a signal that the operation is complete. An analogy. Some telephone customer service lines require you to wait on hold – listening to really bad music – until a customer service representative is available. This is synchronous programming and very wasteful of your time. Some newer customer service lines enable you to enter your telephone number so the customer service representative can call you back when a customer representative becomes available. This approach is much less wasteful of your time because you can do useful things while waiting for the callback. There are several patterns that you can use to write code which executes asynchronously. The most popular pattern in JavaScript is the callback pattern. When you call a function which might take a long time to return a result, you pass a callback function to the function. For example, the following code (which uses jQuery) includes a function named getFlickrPhotos which returns photos from the Flickr website which match a set of tags (such as “dog” and “funny”): function getFlickrPhotos(tags, callback) { $.getJSON( "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: tags, tagmode: "all", format: "json" }, function (data) { if (callback) { callback(data.items); } } ); } getFlickrPhotos("funny, dogs", function(data) { $.each(data, function(index, item) { console.log(item); }); }); The getFlickr() function includes a callback parameter. When you call the getFlickr() function, you pass a function to the callback parameter which gets executed when the getFlicker() function finishes retrieving the list of photos from the Flickr web service. In the code above, the callback function simply iterates through the results and writes each result to the console. Using callbacks is a natural way to perform asynchronous programming with JavaScript. Instead of waiting for an operation to complete, sitting there and listening to really bad music, you can get a callback when the operation is complete. Using Promises The CommonJS website defines a promise like this (http://wiki.commonjs.org/wiki/Promises): “Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time. By utilizing a standard interface, different components can return promises for asynchronous actions and consumers can utilize the promises in a predictable manner.” A promise provides a standard pattern for specifying callbacks. In the WinJS library, when you create a promise, you can specify three callbacks: a complete callback, a failure callback, and a progress callback. Promises are used extensively in the WinJS library. The methods in the animation library, the control library, and the binding library all use promises. For example, the xhr() method included in the WinJS base library returns a promise. The xhr() method wraps calls to the standard XmlHttpRequest object in a promise. The following code illustrates how you can use the xhr() method to perform an Ajax request which retrieves a file named Photos.txt: var options = { url: "/data/photos.txt" }; WinJS.xhr(options).then( function (xmlHttpRequest) { console.log("success"); var data = JSON.parse(xmlHttpRequest.responseText); console.log(data); }, function(xmlHttpRequest) { console.log("fail"); }, function(xmlHttpRequest) { console.log("progress"); } ) The WinJS.xhr() method returns a promise. The Promise class includes a then() method which accepts three callback functions: a complete callback, an error callback, and a progress callback: Promise.then(completeCallback, errorCallback, progressCallback) In the code above, three anonymous functions are passed to the then() method. The three callbacks simply write a message to the JavaScript Console. The complete callback also dumps all of the data retrieved from the photos.txt file. Creating Promises You can create your own promises by creating a new instance of the Promise class. The constructor for the Promise class requires a function which accepts three parameters: a complete, error, and progress function parameter. For example, the code below illustrates how you can create a method named wait10Seconds() which returns a promise. The progress function is called every second and the complete function is not called until 10 seconds have passed: (function () { "use strict"; var app = WinJS.Application; function wait10Seconds() { return new WinJS.Promise(function (complete, error, progress) { var seconds = 0; var intervalId = window.setInterval(function () { seconds++; progress(seconds); if (seconds > 9) { window.clearInterval(intervalId); complete(); } }, 1000); }); } app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { wait10Seconds().then( function () { console.log("complete") }, function () { console.log("error") }, function (seconds) { console.log("progress:" + seconds) } ); } } app.start(); })(); All of the work happens in the constructor function for the promise. The window.setInterval() method is used to execute code every second. Every second, the progress() callback method is called. If more than 10 seconds have passed then the complete() callback method is called and the clearInterval() method is called. When you execute the code above, you can see the output in the Visual Studio JavaScript Console. Creating a Timeout Promise In the previous section, we created a custom Promise which uses the window.setInterval() method to complete the promise after 10 seconds. We really did not need to create a custom promise because the Promise class already includes a static method for returning promises which complete after a certain interval. The code below illustrates how you can use the timeout() method. The timeout() method returns a promise which completes after a certain number of milliseconds. WinJS.Promise.timeout(3000).then( function(){console.log("complete")}, function(){console.log("error")}, function(){console.log("progress")} ); In the code above, the Promise completes after 3 seconds (3000 milliseconds). The Promise returned by the timeout() method does not support progress events. Therefore, the only message written to the console is the message “complete” after 10 seconds. Canceling Promises Some promises, but not all, support cancellation. When you cancel a promise, the promise’s error callback is executed. For example, the following code uses the WinJS.xhr() method to perform an Ajax request. However, immediately after the Ajax request is made, the request is cancelled. // Specify Ajax request options var options = { url: "/data/photos.txt" }; // Make the Ajax request var request = WinJS.xhr(options).then( function (xmlHttpRequest) { console.log("success"); }, function (xmlHttpRequest) { console.log("fail"); }, function (xmlHttpRequest) { console.log("progress"); } ); // Cancel the Ajax request request.cancel(); When you run the code above, the message “fail” is written to the Visual Studio JavaScript Console. Composing Promises You can build promises out of other promises. In other words, you can compose promises. There are two static methods of the Promise class which you can use to compose promises: the join() method and the any() method. When you join promises, a promise is complete when all of the joined promises are complete. When you use the any() method, a promise is complete when any of the promises complete. The following code illustrates how to use the join() method. A new promise is created out of two timeout promises. The new promise does not complete until both of the timeout promises complete: WinJS.Promise.join([WinJS.Promise.timeout(1000), WinJS.Promise.timeout(5000)]) .then(function () { console.log("complete"); }); The message “complete” will not be written to the JavaScript Console until both promises passed to the join() method completes. The message won’t be written for 5 seconds (5,000 milliseconds). The any() method completes when any promise passed to the any() method completes: WinJS.Promise.any([WinJS.Promise.timeout(1000), WinJS.Promise.timeout(5000)]) .then(function () { console.log("complete"); }); The code above writes the message “complete” to the JavaScript Console after 1 second (1,000 milliseconds). The message is written to the JavaScript console immediately after the first promise completes and before the second promise completes. Summary The goal of this blog entry was to describe WinJS promises. First, we discussed how promises enable you to easily write code which performs asynchronous actions. You learned how to use a promise when performing an Ajax request. Next, we discussed how you can create your own promises. You learned how to create a new promise by creating a constructor function with complete, error, and progress parameters. Finally, you learned about several advanced methods of promises. You learned how to use the timeout() method to create promises which complete after an interval of time. You also learned how to cancel promises and compose promises from other promises.

    Read the article

  • Are Promises/A a good event design pattern to implement even in synchronous languages like PHP?

    - by Xeoncross
    I have always kept an eye out for event systems when writing code in scripting languages. Web applications have a history of allowing the user to add plugins and modules whenever needed. In most PHP systems you have a global/singleton event object which all interested parties tie into and wait to be alerted to changes. Event::on('event_name', $callback); Recently more patterns like the observer have been used for things like jQuery. $(el).on('event', callback); Even PHP now has built in classes for it. class Blog extends SplSubject { public function save() { $this->notify(); } } Anyway, the Promises/A proposal has caught my eye. It is designed for asynchronous systems, but I'm wondering if it is also a good design to implement now that even synchronous languages like PHP are changing. Combining Dependency Injection with Promises/A seems it might be the best combination for handling events currently.

    Read the article

  • Windows 8 Promises Less Painful Security Updating

    Earlier this week, a company representative noted that Windows users can look forward to a more streamlined updating process that reduces pesky restarts that often cause interruptions at some of the most inconvenient times. In a MSDN blog post, Windows Update group program manager Farzana Rahman discussed the ways in which automatic updating in Windows 8 will provide an enhanced user experience characterized by minimal interruptions. Rahman acknowledged that the automatic updating process and restarts is one of hot topics that often comes up with Windows due to the untimely interruptions that...

    Read the article

  • Marvell promises $100 tablet for students

    <b>LinuxDevices:</b> "Marvell announced its intent to deliver a $100, Android-ready tablet computer built around a 1GHz Armada 600 series processor. Aimed at students, the "Moby" will offer WiFi, Bluetooth, GPS, an FM receiver, and Adobe Flash compatibility, the company says."

    Read the article

  • Microsoft Promises Plenty of Surprises for E3 2010, with Project Natal Headlining the Show

    With the E3 Expo 2 1 just around the corner there is plenty of buzz circling around what Microsoft will bring to the table. This tech-driven three-day event takes place this year on June 15 16 and 17 at the Los Angeles Convention Center. Fans of Microsoft as well as their competitors will likely be waiting with anticipation as to what Microsoft plans to introduce to the world.... Microsoft BPOS - $10 Per User Per Month* *Includes a 12-month subscription. Minimum 5 seats required.

    Read the article

  • Microsoft Patch Tuesday Promises Critical Updates

    Microsoft revealed some plans last week for its upcoming Patch Tuesday release that should keep IT professionals busy. The latest Patch Tuesday falls on June 14 and it will bring with it 16 bulletins from Microsoft focused on fixing 34 vulnerabilities that stretch across several of the company s products.... Microsoft? Windows Azure Host, Scale, and Manage Web Apps In The Cloud. Learn More About Azure.

    Read the article

  • Secondment promotion promises

    - by user75460
    I'm a Java developer at a large FTSE 30 company. My line manager approached me and asked if I'd like to be the teams lead developer. I was keen to accept. Initially he said I'd be acting-up for 3 months, then changed his tune and said I would be doing a 6 month secondment. During this time, he has got himself promoted and I have a new line manager. I have been very successful during this secondment and reviews have been overwhelmingly positive: both from my former line manager and current line manager. However, six months on, no lead role has been created in the organization and a new director has re-organised the structure of the team: two senior roles (senior Android and senior iOS) are going to be created. I feel a bit put-out that my secondment has amounted to nothing. I could have just done nothing and then applied for the senior role 6 months later (which I feel aren't as marketable as Lead developer). During my secondment I have basically become TA, senior developer, line manager and general go-to guy for all things (across Android and iOS). What do you think I should do, and has my company abused it's position? I feel they have offered a secondment to a role that they never really planned to create. During this time I have received no financial benefit for doing a more senior role.

    Read the article

  • how to use q.js promises to work with multiple asynchronous operations

    - by kimsia
    Note: This question is also cross-posted in Q.js mailing list over here. i had a situation with multiple asynchronous operations and the answer I accepted pointed out that using Promises using a library such as q.js would be more beneficial. I am convinced to refactor my code to use Promises but because the code is pretty long, i have trimmed the irrelevant portions and exported the crucial parts into a separate repo. The repo is here and the most important file is this. The requirement is that I want pageSizes to be non-empty after traversing all the dragged'n dropped files. The problem is that the FileAPI operations inside getSizeSettingsFromPage function causes getSizeSettingsFromPage to be async. So I cannot place checkWhenReady(); like this. function traverseFiles() { for (var i=0, l=pages.length; i<l; i++) { getSizeSettingsFromPage(pages[i], calculateRatio); } checkWhenReady(); // this always returns 0. } This works, but it is not ideal. I prefer to call checkWhenReady just ONCE after all the pages have undergone this function calculateRatio successfully. function calculateRatio(width, height, filename) { // .... code pageSizes.add(filename, object); checkWhenReady(); // this works but it is not ideal. I prefer to call this method AFTER all the `pages` have undergone calculateRatio // ..... more code... } How do I refactor the code to make use of Promises in Q.js?

    Read the article

  • RDF and OWL: Have these delivered the promises of the Semantic Web?

    - by Dark Templar
    These days I've been learning a lot about how different scientific fields are trying to move their data over to the Semantic Web in order to "free up data from being stored in isolated silos". I read a lot about how these fields are saying how their efforts are implementing the "visions" of the Semantic Web. As a learner (and from purely a learning perspective) I was curious to know why, if semantic technology is deemed to be so powerful, the efforts have been around for years but myself and a lot of people I know have never even heard of it until very recently? Also, I don't come across any scholarly articles deeming "oh, our inferencing engine was able to make such and such discovery, which is helping us pave our way to solving...." etc. It seems that there are genuine efforts across different institutions, fields, and disciplines to shift all their data to a "semantic" format, but what happens after all that's been done? All the ontologies have been created/unified, and then what?

    Read the article

  • How do you remind your Scrum Product Owner about his promises/actions?

    - by Felix Ogg
    ** EDIT: Rephrased the question to re-focus ** Our Scrum team meets as seldomly as possible, but we meet with the product owner every chance we get. We track everyone's agreed action points (particularly theirs). We are 100% agile, but our product owner lives in traditional world, we remain off-site. We facilitate him in crossing over to our fast-paced world. There's not much wrong. The team and the PO are in good spirits. PO is present at every meeting and positively energized. Just imagine this person as a 70 year old, slow grandpa, who is forgetful, yet kind. In reality he isn't, but he is used to a working environment (public servants) that is much slooooower. Manyana-manyana etc. It is frustrating for my team to cooperate: PO lives in a non-prioritized environment, and everyone in it has learned the productivity-technique of NGTD (Not Getting Things Done). He WANTS to, it's just that he forgets or 'sinks' somewhere along the away. We have experimented with a text file, maintained by the Scrum master (low-tech), which he broadcasts by e-mail every day JIRA, our issue tracker. Turns out this is nice for programmers, but too steep for 'regular people' I Googled for Issue tracking webtools but came up empty handed: All tools are aimed at IT issue tracking, instead of meeting action point tracking/planning for mere mortals. I did find TODO-lists like RememberTheMilk, but they don't track comments, and - to be honest - I doubt we could get our product owner to use it (too complicated). We have three requirements: Register action points, assign to a team member and a deadline Offer anyone to 'comment' on progress of any action point Do not build our own tool from scratch We do not need: - impressive authorization models, - multi-project, - workflow, - crosslinking. Is there any trick/tool you use to assist your product owner 'fly' like the rest of the rest of the team? Communication before tools I agree with the general consensus that one should not try to apply technology to a communication problem, however in this case I am merely looking for a tool to save me time in setting up prioritized lists. I found www.thymer.com today, may be what I am looking for. The guys are cool. It is getting rather feature-bloated though.

    Read the article

1 2 3 4 5 6 7 8  | Next Page >