


Using Promise to encapsulate FileReader_javascript skills under javascript
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.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor