A brief introduction to ES6 Promise

一个新手
Release: 2017-09-21 09:24:24
Original
1338 people have browsed it

ES6, in order to solve the problem of callback hell, Promise was launched, which literally means a promise. Many articles introducing promises are the kind that make people dizzy at first sight. I have been confused for a long time. Today, from my Let’s talk about it ourselves, what exactly is a promise?
Promise is an object (many people will say, are you talking nonsense? Everything in js is an object). You are right. . .
A promise is an object that is called inside the object; the most common way to write it is:

function GetPromise(someting){ let p = new Promise(resolve,reject) //dosometing resolve(str); reject(str) } return p }
Copy after login

This is the most common way to create and use a promise, and its calling method is

GetPromise(somgting).then(function(){}).catch(function(){})
Copy after login

I am lazy, Many people are going to curse at this time. What is then, what is catch, and where does resolve come from, and where does reject come from. When I first came into contact, I was thinking about this problem, but I couldn’t find it after searching online. Tell me well. Now let me explain it in the simplest way. Then is a success callback and catch is an exception callback, so everyone can understand. Everyone will definitely use judgment when writing code. For example,

if(a=1){ alert('我好帅啊‘) }else{ alert('我怎么这么帅’) }
Copy after login

determines which statement to trigger by judging a. Promise is just this advanced writing method. The resolve provided internally is bound to then and reject. To bind the catch, when we instantiate the promise object, we judge inside it when to trigger which callback. When actually using it, we bind the specific callback through then and catch. When we use promises to perform asynchronous operations, we abstract all successful callbacks into resolve and failure callbacks into reject. In actual calls, we bind specific callback functions through then and catch', which is more elegant and abstract, of course. There are more methods in Promise, but I just want to summarize how to get started. No matter how complicated it is, I won't explain it.

The above is the detailed content of A brief introduction to ES6 Promise. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!