[Effective JavaScript note] 68th: Clean asynchronous logic with promise mode

Source: Internet
Author: User

A popular alternative to building asynchronous APIs is to use promise (sometimes referred to as deferred or future) mode. Asynchronous APIs that have been discussed in this chapter use callback functions as parameters.

downloadAsync(‘file.txt‘,function(file){  console.log(‘file:‘+file);});

The Promise-based API does not receive callback functions as parameters. Instead, it returns a Promise object that receives the callback function through its own then method.

var p=downloadP(‘file.txt‘);p.then(function(file){  console.log(‘file: ‘+file);});

There is no difference from the original version. But the power of promise lies in their composition. The callback function passed to the then method not only has an impact, but can also produce results. A new promise can be constructed by returning a value from the callback function.

var fileP=downloadP(‘file.txt‘);var lengthP=fileP.then(function(file){  return file.length;});lengthP.then(function(length){  console.log(‘length: ‘+length);});

One way to understand promise is to interpret it as an object that represents the final value. It encapsulates a concurrent operation that has not yet completed, but eventually produces a result value. The then method allows us to provide a type of promise object that represents the final value, and produces a new Promise object that represents another type of final value, regardless of what the callback function returns.
The ability to construct new promise from existing promise offers great flexibility and has some simple but powerful idioms. For example, construct a utility to stitch the results of multiple promise.

var filesP=join(downloadP(‘file1.txt‘),               downloadP(‘file2.txt‘),               downloadP(‘file3.txt‘));filesP.then(function(files){  console.log(‘file1:‘+files[0]);  console.log(‘file2:‘+files[1]);  console.log(‘file3:‘+files[2]);});

The Promise Library also often provides a tool function called when, which is similar in use.

var fileP1=downloadP(‘file1.txt‘),    fileP2=downloadP(‘file2.txt‘),    fileP3=downloadP(‘file3.txt‘);when([fileP1,fileP2,fileP3],function(files){  console.log(‘file1:‘+files[0]);  console.log(‘file2:‘+files[1]);  console.log(‘file3:‘+files[2]);});

Part of the reason for making promise an excellent abstraction level is by contacting the result with the return value of the then method, or by using tool functions such as join to form promise, rather than sharing data structures among parallel callback functions. is inherently secure because it avoids the data competition discussed in article 66. Even the most cautious programmers may make simple mistakes when saving the results of an asynchronous operation to a shared variable or data structure.

var file1,file2;downloadAsync(‘file1.txt‘,function(file){  file1=file;});downloadAsync(‘file2.txt‘,function(file){  file1=file;});

Promise avoids this bug, the combination of simple styles promise avoids modifying shared data.
Note that an ordered chain of asynchronous logic can actually be used in an orderly promise, rather than in a cumbersome nesting pattern shown in 62. Error handling is automatically propagated through promise. When you concatenate a collection of asynchronous operations through promise, you can provide a simple error callback function for the entire sequence instead of passing the error callback function to each step, as shown in the code in 63.
Despite this, it is sometimes useful to deliberately create some kind of data competition. Promise provides a good mechanism for some of them. For example, an application might want to try to download the same file from several different servers at the same time, and select the one that was first completed. The select (or choose) tool function receives several promise and produces a promise whose value is the first file to complete the download. In other words, several promise compete with each other.

var fileP=select(downloadP(‘http://e1.com/file.txt‘),downloadP(‘http://e2.com/file.txt‘),downloadP(‘http://e3.com/file.txt‘));fileP.then(function(file){  console.log(‘file: ‘+file);});

Another use of the Select function is to provide a time-out to terminate long operations.

var fileP=select(downloadP(‘http://e1.com/file.txt‘),timeoutErrorP(2000));fileP.then(function(file){  console.log(‘file: ‘+file);},function(error){  console.log(‘I/O error or timeout: ‘+error);});

Here is the mechanism of the error callback function as the second argument to promise's then method. Tips

    • Promise represents the final value, which results when the parallel operation is completed

    • Using promise to combine different parallel operations

    • Use promise-mode APIs to avoid data contention

    • Use Select (also known as choose) when required for intentional competitive conditions

Extended reading Promise https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

[Effective JavaScript note] 68th: Clean asynchronous logic with promise mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.