Promise encapsulates FileReader under javascript

  • 2020-12-22 17:33:12
  • OfStack

Promise is a good choice when dealing with asynchrony, reducing nesting levels and making code more readable and logical. ES6 added it to the specification, and jQuery 3.0 also modified the implementation to be closer to the specification (3.0 announcement). Some new elements like.fetch () are native to "thenable", but most of the old API relies on callbacks, so we can simply repackage them to avoid the nesting trap and enjoy the Promise experience.

General use of Promise 1
Let's look at the common use of Promise.


//  The statement  Promise  object 
var p = new Promise(function (resolve, reject) {
 //  No matter when, it's time to execute then And then call  resolve
 setTimeout(function () { 
  resolve(1);
 }, 5000);

 //  Or whatever the problem is, call it  reject
 if (somethingWrong) {
  reject('2');
 }   
});
  
//  use  Promise  object 
p.then(function (num) {
 //  Corresponding to the above  resolve
 console.log(num); // 1
}, function (num) {
 //  Corresponding to the above  reject
 console.log(num); // 2
});

The driver model of Promise is not complex: any operation is assumed to have only two outcomes, success or failure. Then you just need to call the right program at the right time and go to the right next steps. .then (), as the name implies, means the next step, and when Promise has the result in front of it -- that is, after calling resolve or reject -- it starts the corresponding handler.

Once the Promise instance is created, the execution starts, and we need to determine the result, such as successfully loading, meeting a certain condition, and so on. A series 1 operation can be completed by series.then (). Each call to.then () creates a new instance of Promise, which silently waits for the state of the previous instance to change before executing.

Encapsulation FileReader
Next, start encapsulating. The idea is simple. In addition to providing various read methods, FileReader also has several event hooks, of which onerror and onload are obvious ways to judge whether a task is complete or not. If the load is successful, the file contents will be used, so it is 10 minutes to pass the file or file contents 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 really useful, there are also 1 actions to verify file types, but they are not related to the main idea of this article. The core of this code is to create an Promise object and call the resolve method until the FileReader read is complete, or call the reject method if something goes wrong.

Use the function you just wrapped
You can then use it in your project:


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

.ES50en () supports two parameters, the first starting on success of Promise and the second naturally starting on failure. The same effect can be achieved with.catch (). In addition to being more readable, the Promise object returned can be passed arbitrarily, allowing for a lot of imagination.

Continue. then ()
So let's concatenate some more operations (if I wanted to write a breakpoint, I'll do it later) :

Copy all into notes reader(file)


 .then(function (reader) {
  return new Promise(function (resolve, reject) {
   //  Just pause it 5 Seconds... 
   setTimeout(function () {
    resolve(reader.result); 
   }, 5000);
  });
 })
 .then(function (content) {
  console.log(content);
 });

Above is the entire content of this article, I hope to help you with your study.


Related articles: