Home  >  Article  >  Web Front-end  >  Using Promise to encapsulate FileReader_javascript skills under javascript

Using Promise to encapsulate FileReader_javascript skills under javascript

WBOY
WBOYOriginal
2016-05-16 15:14:401608browse

Promise is a good choice when dealing with asynchronous processing. It can reduce the nesting level, making the code more readable and the logic clearer. ES6 added it to the specification, and jQuery 3.0 also modified the implementation to move closer to the specification (3.0 release announcement). Some new elements such as .fetch() are natively "thenable", but most previous APIs still rely on callbacks. At this time, we only need to re-encapsulate them to avoid nesting traps and enjoy the pleasure brought by Promise. experience.

General usage of Promise
Let’s first look at the general usage of Promise.

// 声明 Promise 对象
var p = new Promise(function (resolve, reject) {
 // 不管啥时候,该执行then了,就调用 resolve
 setTimeout(function () { 
  resolve(1);
 }, 5000);

 // 或者不管啥问题,就调用 reject
 if (somethingWrong) {
  reject('2');
 }   
});
  
// 使用 Promise 对象
p.then(function (num) {
 // 对应上面的 resolve
 console.log(num); // 1
}, function (num) {
 // 对应上面的 reject
 console.log(num); // 2
});

The driving model of Promise is not complicated: any operation is assumed to have only two results, success or failure. Then you just need to call the right program at the right time and enter the appropriate subsequent steps. .then(), as the name suggests, means the next step. After the previous Promise has a result—that is, calling resolve or reject—the corresponding processing function is started.

The Promise instance will start executing after it is created, and we need to determine the result ourselves, such as successful loading, or meeting a certain condition, etc. By concatenating .then(), a series of operations can be completed. Each call to .then() will create a new Promise instance, which will wait quietly for the state of the previous instance to change before starting execution.

Pack FileReader
The next step is to start packaging. The idea is very simple. In addition to providing various read methods, FileReader also has several event hooks, among which onerror and onload can obviously be used as the basis for judging whether the task is completed. If the loading is successful, the file content will be used, so it is necessary to pass the file or file content to the next step.

The final completed 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 some operations for verifying file types, but they are not related to the main purpose of this article and will not be listed. The core of this code is to create a Promise object, wait for the FileReader to complete reading, and call the resolve method, or call the reject method when a problem occurs.

Use the function just encapsulated
You can now use it in your project:

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

.then() supports two parameters. The first one is started when the Promise succeeds, and the second one is naturally started when it fails. The same effect can be achieved using .catch(). In addition to better readability, the benefit of Promise is that the returned Promise object can be passed arbitrarily, and chain calls can be continued, leaving a lot of room for imagination.

Continue .then()
So we might as well connect more operations in series (I originally wanted to write a breakpoint resume, but I’ll talk about it later):

Select all and copy them into the note reader(file)

 .then(function (reader) {
  return new Promise(function (resolve, reject) {
   // 就随便暂停个5秒吧……
   setTimeout(function () {
    resolve(reader.result); 
   }, 5000);
  });
 })
 .then(function (content) {
  console.log(content);
 });

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn