Examples to explain Promis asynchronous programming
The following editor will bring you an example explanation of Promise asynchronous programming. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
The example is as follows:
//1.解决异步回调问题
//1.1 如何同步异步请求
//如果几个异步操作之间并没有前后顺序之分,但需要等多个异步操作都完成后才能执行后续的任务,无法实现并行节约时间
const fs = require('fs');
let school = {};
fs.readFile('./name.txt','utf8',function (err,data) {
school.name = data;
});
fs.readFile('./age.txt','utf8',function (err,data) {
school.age = data;
});
console.log(school);
//1.2如何解决回调地狱
//在需要多个操作的时候,会导致多个回调函数嵌套,导致代码不够直观,就是常说的回调地狱
const fs = require('fs');
fs.readFile('./content.txt','utf8',function (err,data) {
if(err)console.log(err);
fs.readFile(data,'utf8',function (err,data) {
if(err)console.log(err);
console.log(data);
})
});
//2.Promise
//Promise本意是承诺,在程序中的意思就是承诺我过一段时间后会给你一个结果。 什么时候会用到过一段时间?答案是异步操作,异步是指可能比较长时间才有结果的才做,例如网络请求、读取本地文件等
//3.Promise的三种状态
//例如媳妇说想买个包,这时候他就要"等待"我的回复,我可以过两天买,如果买了表示"成功",如果我最后拒绝表示"失败",当然我也有可能一直拖一辈子
//Pending Promise对象实例创建时候的初始状态
//Fulfilled 可以理解为成功的状态
//Rejected 可以理解为失败的状态
//then 方法就是用来指定Promise 对象的状态改变时确定执行的操作,resolve 时执行第一个函数(onFulfilled),reject 时执行第二个函数(onRejected)
//4.构造一个Promise
//4.1 promise的方法会立刻执行
let promise = new Promise(()=>{
console.log('hello');
});
console.log('world');
//4.2 promise也可以代表一个未来的值
const fs = require('fs');
let promise = new Promise((resolve,reject)=>{
fs.readFile('./content.txt','utf8',function (err,data) {
if(err)console.log(err);
resolve(data);
})
});
promise.then(data =>{
console.log(data);
});
//4.3 代表一个用于不会返回的值
const fs = require('fs');
let promise = new Promise((resolve,reject)=>{});
promise.then(data =>{
console.log(data);
});
//4.4 应用状态实现抛硬币
function flip_coin() {
return new Promise((resolve,reject)=>{
setTimeout(function () {
var random = Math.random();
if(random > 0.5){
resolve('正');
}else{
resolve('反');
}
},2000)
})
}
flip_coin().then(data=>{
console.log(data);
},data=>{
console.log(data);
});
//5.实现简单的Promise
function Promise(fn) {
fn((data)=>{
this.resolve(data)
},(data)=>{
this.reject(data);
})
}
Promise.prototype.resolve = function (data) {
this._success(data)
};
Promise.prototype.reject = function (data) {
this._error(data);
};
Promise.prototype.then = function (success,error) {
this._success = success;
this._error = error;
};
//6.Error会导致触发Reject
//可以采用then的第二个参数捕获失败,也可以通过catch函数进行捕获
function flip_coin() {
return new Promise((resolve,reject)=>{
throw Error('没有硬币')
})
}
flip_coin().then(data=>{
console.log(data);
}).catch((e)=>{
console.log(e);
})
//7.Promise.all实现并行
//接受一个数组,数组内都是Promise实例,返回一个Promise实例,这个Promise实例的状态转移取决于参数的Promise实例的状态变化。当参数中所有的实例都处于resolve状态时,返回的Promise实例会变为resolve状态。如果参数中任意一个实例处于reject状态,返回的Promise实例变为reject状态
const fs = require('fs');
let p1 = new Promise((resolve,reject)=>{
fs.readFile('./name.txt','utf8',function (err,data) {
resolve(data);
});
})
let p2 = new Promise((resolve,reject)=>{
fs.redFile('./age.txt','utf8',function (err,data) {
resolve(data);
});
})
Promise.all([p1,p2]).then(([res1,res2])=>{
console.log(res1);
})
//不管两个promise谁先完成,Promise.all 方法会按照数组里面的顺序将结果返回
//8.Promise.race实现选择接受一个数组,数组内都是Promise实例,返回一个Promise实例,这个Promise实例的状态转移取决于参数的Promise实例的状态变化。当参数中任何一个实例处于resolve状态时,返回的Promise实例会变为resolve状态。如果参数中任意一个实例处于reject状态,返回的Promise实例变为reject状态。
const fs = require('fs');
let p1 = new Promise((resolve,reject)=>{
fs.readFile('./name.txt','utf8',function (err,data) {
resolve(data);
});
})
let p2 = new Promise((resolve,reject)=>{
fs.readFile('./age.txt','utf8',function (err,data) {
resolve(data);
});
})
Promise.race([p1,p2]).then(([res1,res2])=>{
console.log(res1,res2);
})
9.Promise.resolve
//返回一个Promise实例,这个实例处于resolve状态。
Promise.resolve('成功').then(data=>{
console.log(data);
})
10.Promise.reject
//返回一个Promise实例,这个实例处于reject状态
Promise.reject('失败').then(data=>{
console.log(data);
},re=>{
console.log(re);
})
//11.封装ajax
function ajax({url=new Error('url必须提供'),method='GET',async=true,dataType='json'}){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open(method,url,async);
xhr.responseType = dataType;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(/^2\d{2}/.test(xhr.status)){
resolve(xhr.response);
}else{
reject(xhr.response);
}
}
}
xhr.send();
});
}
//12.chain中返回结果
Promise.resolve([1,2,3])
.then(arr=>{
return [...arr,4]
}).then(arr=>{
return [...arr,5]
}).then(arr=>{
console.log(arr);
})
//13.chain中返回promise
//then中的结果是promise的resolve后的结果
Promise.resolve('user').then(data=>{
return new Promise(function (resolve,reject) {
fetch('/'+data).then(res=>res.json().then((json)=>{
resolve(json)
}))
})
}).then(data=>{
console.log(data);
});
//改写的更简单些
Promise.resolve('user').then(data=>{
return fetch('/'+data)
}).then(res=>{
return res.json();
}).then(data=>{
console.log(data);
})
//14.async/await
//本质是语法糖,await与async要连用,await后只能跟promise
async function getHello() {
return new Promise((resolve,reject) => {
setTimeout(function () {
resolve('hello');
},2000);
})
}
async function getData () {
var result = await getHello();
console.log(result);
} ;
getData();The above is the detailed content of Examples to explain Promis asynchronous programming. For more information, please follow other related articles on the PHP Chinese website!
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
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1378
52
Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files
Sep 12, 2023 pm 01:15 PM
Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files With the development of the Internet, the file download function has become one of the basic needs of many websites and applications. For scenarios where multiple files need to be downloaded at the same time, the traditional synchronous download method is often inefficient and time-consuming. For this reason, using PHP to download multiple files asynchronously over HTTP has become an increasingly common solution. This article will analyze in detail how to use PHP asynchronous HTTP through an actual development case.
How Swoole supports asynchronous SMTP operations
Jun 25, 2023 pm 12:24 PM
With the continuous development and popularization of the Internet, email has become an indispensable part of people's lives and work, and SMTP (Simple Mail Transfer Protocol) is one of the important protocols for email sending. As an asynchronous network communication framework for PHP, Swoole can well support asynchronous SMTP operations, making email sending more efficient and stable. This article will introduce how Swoole supports asynchronous SMTP operations, including using sync
How Swoole supports asynchronous AMQP operations
Jun 25, 2023 am 08:22 AM
As the volume of Internet business continues to grow, the demand for high concurrency and high performance is getting higher and higher, and Swoole, as a network communication framework for PHP, is increasingly favored by developers. Among them, Swoole supports asynchronous AMQP, which is one of the more common application scenarios. So let's take a look at how Swoole supports asynchronous AMQP operations. First, we need to clarify what AMQP is. AMQP (AdvancedMessageQueuingProtocol) Advanced
Advanced Guide to Python asyncio: From Beginner to Expert
Mar 04, 2024 am 09:43 AM
Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio
How to use the asynchronous request function in the Vue documentation
Jun 20, 2023 pm 05:55 PM
Vue.js is a popular front-end JavaScript framework that provides a way to build user interfaces in your applications. In the Vue.js documentation, we can find a lot of useful information, especially about how to use asynchronous request functions. Asynchronous request functions are a way to perform asynchronous tasks in an application. They are used to get data from the server, process input, validate forms, etc. Generally speaking, asynchronous request functions need to be combined with Java functions such as Promise, async and await.
Asynchronous and non-blocking technology in Java exception handling
May 01, 2024 pm 05:42 PM
Asynchronous and non-blocking techniques can be used to complement traditional exception handling, allowing the creation of more responsive and efficient Java applications: Asynchronous exception handling: Handling exceptions in another thread or process, allowing the main thread to continue executing, avoiding blocking. Non-blocking exception handling: involves event-driven exception handling when an I/O operation goes wrong, avoiding blocking threads and allowing the event loop to handle exceptions.
PHP asynchronous coroutine development: speed up data caching and read and write operations
Dec 18, 2023 pm 01:09 PM
PHP asynchronous coroutine development: accelerating data caching and read and write operations. In actual application development, data caching and read and write operations are common performance bottlenecks. In order to improve system efficiency and user experience, PHP asynchronous coroutine technology can be used to accelerate these operations. This article will introduce the basic concepts and principles of PHP asynchronous coroutines and provide specific code examples. 1. The concept and principle of asynchronous coroutine Asynchronous coroutine is an efficient concurrent programming technology that uses a single thread to achieve lightweight task scheduling and collaboration. Compared with traditional multi-threaded or multi-process concurrent programming
How to use ThinkPHP6 for asynchronous logging operations?
Jun 12, 2023 am 09:57 AM
With the rapid development of the Internet, logging services have become an essential module for every large-scale web application. In order to facilitate various needs such as error troubleshooting and performance monitoring, this article will introduce how to use the ThinkPHP6 framework to perform asynchronous logging operations. 1. What is logging? In the field of computer science, logging refers to recording events and information that occur in a computer system. Typically, these records are stored in files or databases. Logging helps to understand the system operating status, detect and solve problems in a timely manner


