Yes. Promise is a new reference type in ECMAScript 6, which represents the final completion or failure of an asynchronous operation. Promise solves the problem of overly complex logic writing in asynchronous programming calling code. When the network request is very complex, callback hell will occur. In this way, if these codes are written together, they will look very complicated and not conducive to reading. If you use Promises will make the code look more beautiful and elegant.

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
ECMAScript 6 adds complete support for the Promises/A specification, that is, the Promise type. Once launched, Promise became extremely popular and became the dominant asynchronous programming mechanism. All modern browsers support ES6 expectations, and many other browser APIs are based on expectations.
Promise is a new reference type in ECMAScript 6, which represents the final completion or failure of an asynchronous operation.
1. What does the promise function do?
The promise function solves the problem of overly complex writing of asynchronous programming calling code logic. When the network request is very complex, it will Callback hell appears, so if these codes are written together, they will look very complicated and not conducive to reading. If you use promise, the code will look more beautiful and elegant.
2. Promise 3 A state
First of all, when we have an asynchronous operation in development, we can wrap a Promise for the asynchronous operation
There will be three states after the asynchronous operation
pending:等待状态,比如正在进行网络请求,或者定时器没有到时间。 fulfill:满足状态,当我们主动回调了resolve时,就处于该状态,并且会回调.then() reject:拒绝状态,当我们主动回调了reject时,就处于该状态,并且会回调.catch()
3. Implement
1, then and catch
1. Functions in a pending state are synchronous and will be executed immediately
2.then and catch are asynchronous. Even if there is no asynchronous operation in the promise object and the then method or catch is executed immediately, the two methods here may be added to the event queue to wait for execution
//参数 函数(resolve,reject)
new Promise((resolve, reject) => {
setTimeout(() => {
//请求成功的时候调用resolve
resolve('22222')
//请求失败的时候调用reject
reject('error message')
}, 1000)
}).then((data) => { //请求成功处理函数
console.log(data)
}).catch((err) => { //请求失败处理函数
console.log(err)
})2. Determine the status
1. If an uncaught error occurs in the pending status processing function, the status will be pending and will directly become the rejected status and can be caught. Capture
var pro = new Promise((resolve, reject) => {
throw new Error("123");
// try{
// throw new Error("123");
// } catch(e) {}
resolve(12);
reject(34);
})
// pro.then(data => {
// console.log(data);
// }, err => {
// console.log(err);
// })
console.log(pro);
pro.then(data => {
console.log(data);
})
pro.catch(data => {
console.log(data);
})3.async and await
1.Use Promise:
const makeRequest = () =>
getJSON().then(data => {
console.log(data)
return "done"
})
makeRequest()2.Use Async :
async and await are proposed by ES7
The role of async:Simplify the creation of promise objects in function return values
General situation Below, async is written at the front of the function, and the return value of the modified function must be a promise object. Only in some special cases will a promise object be returned manually.
Function: Solve asynchronous problems like promise, but its advantage is to make asynchronous code the same as synchronous!!
Note: In synchronous method, we get the result through the return value , the asynchronous method gets the result by relying on the callback function.
Basic syntax used by async and await:
It is to add an async in front of the ordinary function and the call is the same as the ordinary function
Async is generally used in conjunction with await
await is followed by a promise object await must be used in an asynchronous function
const makeRequest = async () => {
// await getJSON()表示console.log会等到getJSON的promise成功reosolve之后再执行。
console.log(await getJSON)
return "done"
}
makeRequest()3. Difference
1. There is an extra aync keyword in front of the function. The await keyword can only be used within functions defined by aync. The async function will implicitly return a promise, and the resolve value of the promise is the value of the function return. (The reosolve value in the example is the string "done")
2. We cannot use await in the outermost code because it is not within the async function.
4.promise method
var r1 = new Promise((resolve,reject) => {
setTimeout(function(){
resolve("我是第一个请求");
},1000)
})
var r2 = new Promise((resolve,reject) => {
setTimeout(function(){
resolve("我是第二个请求");
},3000)
})
var r3 = new Promise((resolve,reject) => {
setTimeout(function(){
resolve("我是第三个请求");
},4000)
})
var r4 = new Promise((resolve,reject) => {
setTimeout(function(){
resolve("我是第四个请求");
},500)
})1.all method
Sometimes we need to wait for two or more requests to return successfully before proceeding In the next step, the all method of promise is to wait for all asynchronous requests to be completed before making the next callback
Promise.all([r1,r2,r3,r4]).then(data => {
console.log(data);
})2.race method
The requests are sent out at the same time. Whoever comes back first will use whose data .
Promise.race([r1,r2,r3,r4]).then(data => {
console.log(data);
})5. Promise encapsulation ajax case
<script>
function toData(obj) {
// 声明一个数组 来装每一组的数据
var arr = [];
if(obj !== null) {
for(var key in obj) {
let str = key + "=" + obj[key];
arr.push(str);
}
return arr.join("&");
}
}
function ajax(obj) {
return new Promise(function(resolve, reject) {
// 给ajax所需要的参数设置默认值
obj.type = obj.type || "get";
obj.async = obj.async|| "true";
obj.dataType = obj.dataType || "json";
obj.data = obj.data || null;
// 开始发送ajax请求
var xhr;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// IE低版本的浏览器
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
// 判断是post请求 还是get请求
if(obj.type === "post") {
xhr.open(obj.type, obj.url, obj.async);
// 设置请求头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(toData(obj.data));
} else {
var url = obj.url + "?" + toData(obj.data);
xhr.open(obj.type, url, obj.async);
xhr.send();
}
// 处理响应体
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(xhr.status);
}
}
}
})
}
ajax({
url : "./data.php",
data : {
name : "jack",
age : 16
}
}).then(res => {
console.log(res);
}, err => {
console.log(err);
})
</script>[Related recommendations: javascript video tutorial, web front-end]
The above is the detailed content of Is promise based on es6?. For more information, please follow other related articles on the PHP Chinese website!
The Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AMReact’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.
React: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AMReact is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.
React vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AMReact is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.
HTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AMThe relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.
React and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AMReact is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent
React and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AMReact is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.
React's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AMReact combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.
React Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PMReact components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.







