What you need to know to get started with Promise
This time I will bring you what you must know when getting started with Promise. What are the precautions that you must know when getting started with Promise. Here are practical cases, let’s take a look.
Promise is a solution for asynchronous programming. Syntactically speaking, Promise is an object from which messages for asynchronous operations can be obtained.
Basic usage of Promise
PromiseConstructor functionAccepts a function as a parameter, and the two parameters of the function are resolve and reject. They are two functions, provided by the JavaScript engine.
The function of the resolve function is to change the state of the Promise object from "uncompleted" to "successful" (that is, from Pending to Resolved), When the asynchronous operation is successful Call and pass the result of the asynchronous operation as a parameter.
The function of the reject function is to change the status of the Promise object from "uncompleted" to "failed" (that is, from Pending to Rejected), When the asynchronous operation fails Call and pass the error reported by the asynchronous operation as a parameter.
Thethen method can accept two callback functions as parameters. The first callback function is called when the state of the Promise object changes to Resolved, and the second callback function is called when the state of the Promise object changes to Reject.
var promise = new Promise( //异步执行,Promise对象创建后会被立即执行 function (resolve,reject) { //耗时很长的异步操作 if('异步处理成功') { resolve(); //数据处理成功时调用 } else { reject(); //数据处理失败时调用 } } )//Promise实例生成以后,可以用then方法分别指定Resolved状态和Reject状态的回调函数。promise.then( function A() { //数据处理成功后执行 }, function B() { //数据处理失败后执行 } )
Let’s take a simple example to simulate the running process of asynchronous operation success and asynchronous operation failure functions.
console.log('starting' promise = Promise("2秒后,我运行了"'异步操作成功了'); }, 2000'异步操作成功后执行我:''异步操作失败后执行我:''我也运行了'
知代码3处的return 'hello' 语句在新建的new Promise对象中并没有被当作参数返回给then()函数内.那么会不会返回给promise了呢?我们用一段代码来测试一下
console.log('starting');var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("2秒后,我运行了"); resolve('异步操作成功了'); //1 //reject('异步操作失败了'); //2 return 'hello'; }, 2000) }) promise.then(function (value) { console.log('异步操作成功后执行我:',value); },function (value) { console.log('异步操作失败后执行我:',value); } ) console.log('我也运行了'); console.log(promise); setTimeout(function () { console.log('5秒后,我执行了'); console.log(promise); },5000);//starting//我也运行了//Promise { pending } //[[PromiseStatus]]:"pending" //[[PromiseValue]]:undefined //proto:Promise {constructor: , then: , catch: , …}//2秒后,我运行了//异步操作成功后执行我: 异步操作成功了//5秒后,我执行了//Promise { resolved } //[[PromiseStatus]]:"resolved" //[[PromiseValue]]:"异步操作成功了" //proto:Promise {constructor: , then: , catch: , …}
It can be seen from the execution results that the variable promise is still an instance of the new Promise object. Therefore, although the return statement is executed, it will not have any impact on the promise instance, which is equivalent to non-existence.
As can be seen from the code tested above, Promise objects have the following two characteristics.
(1) The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation and has three states: Pending (in progress), Resolved (completed, also known as Fulfilled) and Rejected (failed). Only the result of the asynchronous operation can determine which state the current state is,
(2) Once the state changes, it will not change again, and the result can be obtained at any time. There are only two possibilities for the state of a Promise object to change: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will be solidified and will not change again, and will maintain this result. Even if the change has already occurred, if you add a callback function to the Promise object, you will get the result immediately. This is completely different from an event. The characteristic of an event is that if you miss it and listen again, you will not get the result.
resolve(value) VS resolve(Promise)
We will call the resolve function when the asynchronous operation is successful, and its function is to change the state of the Promise object from Pending becomes Resolved, and the result of the asynchronous operation is passed as a parameter to the formal parameter of the first function in the then() method.
So what is the difference between when the parameter passed in is a value and when the parameter passed in is a promise object. Let's look at an example.
When the parameter passed in is a value:
var time = new Date();var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("1秒后,我运行了"); resolve('异步操作成功了'); //1 }, 2000) }).then(function (value) { console.log(value,new Date() - time); })//执行的输出结果为://2秒后,我运行了//异步操作成功了 1002
After about a second or so, we can see that in the callback method of the resolved state, we print out the content in the above comment . We can pass the results of the operation through the resolve method and then use these results in the callback method.
What if we pass in a Promise instance in resolve?
time = promise = Promise("2秒后,我运行了"'异步操作成功了'); 2000 promise2 = Promise(1000 Date() -
promise2 prints out the result after 2 seconds. Strange, didn't we set promise2 to be executed after 1 second?
Simply put, it is because the resolve() function in promise2 passes in the promise object. At this time, the state of the promise object determines the state of the promise, and the return value is passed to the promise.
Promise/A+ stipulates [[Resolve]](promise, x)
2.3.2. If x is a promise instance, then x The status of is used as the status of promise
2.3.2.1. If the status of x is pending, then the status of promise is also pending until the status of x changes.
2.3.2.2. If the status of x is fulfilled, the status of promise is also fulfilled, and the immutable value of x is used as the immutable value of promise.
2.3.2.3.如果x的状态为rejected, promise的状态也为rejected, 并且以x的不可变原因作为promise的不可变原因。
2.3.4.如果x不是对象或函数,则将promise状态转换为fulfilled并且以x作为promise的不可变值。
Promise.prototype.then()
Promise实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的。它的作用是为Promise实例添加状态改变时的回调函数。 前面说过,then方法的第一个参数是Resolved状态的回调函数,第二个参数(可选)是Rejected状态的回调函数。
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
var promise = new Promise(function(resolve, reject) { setTimeout(function() { console.log("2秒后,我运行了"); resolve('异步操作成功了'); //1 }, 2000) }) promise.name = 'promise'; console.log('promise:',promise)var promise2 = promise.then(function (value) { console.log(value); }) promise2.name = 'promise2'; console.log('promise2:',promise2);// promise:// Promise { pending }// [[PromiseStatus]]:"pending"// [[PromiseValue]]:undefined// name:"promise"// proto:Promise {constructor: , then: , catch: , …}// promise2:// Promise { pending }// [[PromiseStatus]]:"pending"// [[PromiseValue]]:undefined// name:"promise2"// proto:Promise {constructor: , then: , catch: , …}
我们可以知道promise.then()方法执行后返回的是一个新的Promise对象。也就是说上面代码中的promise2是一个Promise对象,它的实现效果和下面的代码是一样的,只不过在then()方法里,JS引擎已经自动帮我们做了。
promise2 = new Promise(function (resolve,reject) {})
既然在then()函数里已经自动帮我实现了一个promise对象,但是我要怎么才能给resolve()或reject()函数传参呢?其实在then()函数里,我们可以用return()的方式来给promise2的resolve()或reject()传参。看一个例子。
promise = Promise("2秒后,我运行了"'异步操作成功了'); }, 2000 promise2 = promise.then( (1 promise3 = promise2.then('is:''error:'= 'promise2'3000
Promise与错误状态处理
.then(null, rejection),用于指定异步操作发生错误时执行的回调函数。下面我们做一个示例。
var promise = new Promise(function(resolve, reject) { setTimeout(function () { reject('error'); },2000); }).then(null,function(error) { console.log('rejected', error) });//rejected error
我们知道then()方法执行后返回的也是一个promise对象,因此也可以调用then()方法,但这样的话为了捕获异常信息,我们就需要为每一个then()方法绑定一个.then(null, rejection)。由于Promise对象的错误信息具有“冒泡”性质,错误会一直向后传递,直到被捕获为止。因此Promise为我们提供了一个原型上的函数Promise.prototype.catch()来让我们更方便的 捕获到异常。
我们看一个例子
var promise = new Promise(function(resolve, reject) { setTimeout(function () { reject('error'); },2000); }).then(function(value) { console.log('resolve', value); }).catch(function (error) { console.log(error); })//运行结果//error
上面代码中,一共有二个Promise对象:一个由promise产生,一个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。
但是如果用.then(null, rejection)方法来处理错误信息,我们需要在每一个rejection()方法中返回上一次异常信息的状态,这样当调用的then()方法一多的时候,对会对代码的清晰性和逻辑性造成影响。
所以,一般来说,不要在then方法里面定义Reject状态的回调函数(即then的第二个参数),总是使用catch方法。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of What you need to know to get started with Promise. 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

Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

As a widely used programming language, C language is one of the basic languages that must be learned for those who want to engage in computer programming. However, for beginners, learning a new programming language can be difficult, especially due to the lack of relevant learning tools and teaching materials. In this article, I will introduce five programming software to help beginners get started with C language and help you get started quickly. The first programming software was Code::Blocks. Code::Blocks is a free, open source integrated development environment (IDE) for

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.
