Promises are 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 revised the implementation to move closer to the specification (3.0 announcement). Some new elements such as.fetch() are natively “thenable,” but most of the older apis rely on callbacks, and at this point we can simply repackage them to avoid nesting traps and enjoy the Promise experience.

I Promise.

Let’s start with the general use of Promise.

Var p = new Promise(function (resolve, reject) { Resolve setTimeout(function () {resolve(1); }, 5000); Reject if (somethingWrong) {reject('2'); }}); // use the Promise object p.chen (function (num) {resolve console.log(num); }, reject console.log(num) {reject console.log(num); / / 2});Copy the code

The Promise driver model is uncomplicated: any action is assumed to have only two outcomes, success or failure. Just call the right program at the right time and proceed to the right next step. .then(), as the name suggests, is the next step. Once the previous Promise has a result — resolve or reject — the corresponding handler is launched.

Once a Promise instance is created, it starts to execute, and it’s up to us to determine the outcome, such as loading successfully, or meeting certain conditions, etc. A series of operations can be done by concatenating.then(). Each call to.then() creates a new Promise instance, which quietly waits for the state of the previous instance to change before starting execution.

encapsulationFileReader

Next, the encapsulation begins. FileReader provides a variety of read methods as well as several event hooks, including onError and onLoad, which can obviously be used to determine whether a task is complete. If the load is successful, the contents of the file are needed, so it is necessary to pass the file or contents of the file 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); }}); }Copy the code

In order to really come in handy, there are also some actions to verify file types, which are not relevant to this article. The core of this code is to create a Promise object and wait for the FileReader to finish reading and call either resolve or Reject if there is a problem.

Github Gist has one too.

Use the function you just wrapped

Now you can use it in your project:

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

.then() supports two arguments, the first starting when a Promise succeeds and the second, naturally, starting when a Promise fails. The same effect can be achieved with.catch(). The benefits of promises aside from being more readable, the returned Promise objects can be passed around at will, continuing with chain calls, leaving a lot to the imagination.

Continue to.then()

So we might as well concatenate some more operations:

Reader (file). Then (function (reader) {return new Promise(function (resolve, reject) { setTimeout(function () { resolve(reader.result); }, 5000); }); }) .then(function (content) { console.log(content); });Copy the code

conclusion

This is actually the first time I’ve used Promise, and the last time I translated jQuery’s announcement I had only a half-understanding of it and a very confusing interpretation of it. I love learning to use new technologies on side projects, and I recently gave it a try while developing the Chrome plugin, and it was great. The process is much more complicated and much easier than I thought it would be. It’s a great design that solves a lot of practical problems and gives me a lot of inspiration. I think I’ll be doing this in a lot of places in the future.

reference

Apart from the links in the first paragraph, there are some articles worth checking out.

ECMAScript 6 Getting started: Promise objects