Use Promise to encapsulate FileReader and promisefilereader in javascript

Source: Internet
Author: User

Use Promise to encapsulate FileReader and promisefilereader in javascript

Promise is a good choice when processing Asynchronization. It can reduce the nested hierarchy and make the Code better read and the logic clearer. ES6 adds it to the specification, and jQuery 3.0 also changes the implementation to move closer to the specification (3.0 published an announcement ). Some new elements such. fetch () is native and "thenable". However, most previous APIs still need to rely on callback. At this time, we only need to re-encapsulate them to avoid nested traps, enjoy the pleasant experience of Promise.

General Promise usage
Let's take a look at the general usage of Promise.

// Declare the Promise object var p = new Promise (function (resolve, reject) {// when then is executed, call resolve setTimeout (function () {resolve (1) ;}, 5000); // or whatever the problem is, call reject if (somethingWrong) {reject ('2 ');}}); // use the Promise object p. then (function (num) {// corresponds to the above resolve console. log (num); // 1}, function (num) {// corresponds to the above reject console. log (num); // 2 });

The driver model of Promise is not complex: any operation, assuming that it has only two results, success or failure. So you only need to call the appropriate program at the right time and enter the appropriate subsequent steps .. Then (), as its name implies, is the meaning of the next step. The current Promise starts the corresponding processing function after it has the result called resolve or reject.

After the Promise instance is created, the execution starts. We need to determine the result, for example, whether the instance is loaded successfully or meets certain conditions. You can perform a series of operations by concatenating. then. Every time you call. then (), a new Promise instance is created. It will wait for the previous instance to change its status before execution.

Encapsulate FileReader
Next we start encapsulation. The idea is simple. In addition to various read methods, FileReader also has several event hooks. onerror and onload can be clearly used as the basis for determining whether a task is completed. If the file content is loaded successfully, it is necessary to pass the file or file content to the next step.

The final code is as follows:

function reader (file, options) { options = options || {}; return new Promise(function (resolve, reject) {  let reader = new FileReader();  reader.onload = function () {   resolve(reader);  };  reader.onerror = reject;  if (options.accept && !new RegExp(options.accept).test(file.type)) {   reject({    code: 1,    msg: 'wrong file type'   });  }  if (!file.type || /^text\//i.test(file.type)) {   reader.readAsText(file);  } else {   reader.readAsDataURL(file);  } });}

In order to be practical, there are some operations to verify the file type, but it has nothing to do with the subject of this article, and it is skipped. The core of this Code is to create a Promise object and call the resolve method after the FileReader completes reading, or call the reject method when a problem occurs.

Use the encapsulated Function
Next we can use it in the project:

reader(file) .then(function (reader) {  console.log(reader.result); }) .catch(function (error) {  console.log(error); });

. Then () supports two parameters. The first parameter is enabled when Promise is successful, and the second parameter is started when Promise fails. Use. catch () to achieve the same effect. In addition to better readability, the returned Promise object can also be passed at will to continue the chain call, which is quite imaginative.

Continue. then ()
So we might as well concatenate more operations (if you want to write a resumable data transfer, let's talk about it later ):

Select All copies and put them into the notes reader (file)

. Then (function (reader) {return new Promise (function (resolve, reject) {// just pause for 5 seconds ...... SetTimeout (function () {resolve (reader. result) ;}, 5000 );});}). then (function (content) {console. log (content );});

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Six features of the Promise mode in JavaScript asynchronous programming
  • Detailed introduction to the Javascript asynchronous programming model Promise Mode
  • Detailed introduction to asynchronous programming specification Promises/A in Javascript
  • Use q. js in node. js to implement api promise
  • Use javascript with fileReader to upload images
  • Use Promise in NodeJS to encapsulate asynchronous Functions
  • Example: How to Use Promise in JavaScript

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.