My seventh day at the front end of Le byte learning – promise learning

Time:2021-1-28

1、 What is promise?

PromiseIt is a new solution for asynchronous programming introduced by ES6. Note: the old is a simple callback function

Syntactically, it is a constructor that encapsulates asynchronous tasks and processes the results. In terms of function:PromiseObject is used to encapsulate an asynchronous operation and get its valueSuccess / failureThe result value of.

PromiseThe biggest advantage is that it can solve the problem of callback hell, and it is more flexible and convenient in specifying callback and error handlingPromiseIn modern projects, whether it is web or app projects are widely used, whether it is front-end or back-end can see its shadow, at the same time it is nowHigh frequency questions in interview

2、 Promise first experience

2.1 reading file contents in nodejs environment

Requirement: read the file in the current directory content.txt And output.

//Introducing FS module
const fs = require(‘fs’)

//Callback function form
// fs.readFile(‘./file/content.txt’, (err, data) => {
/// / if there is an error, an error is thrown
//   if(err) throw err

//   console.log(data.toString());
// })

//Promise new
let p = new Promise((resolve, reject) => {
fs.readFile(‘./file/content.txt’, (err, data) => {
if (err) reject(err);
resolve(data);
})
})

p.then(value =>{
console.log(value.toString());
},reason =>{
console.log(reason);
})

output:

Hello Promise,This is Content
1

2.2 encapsulating Ajax

Requirement: encapsulate Ajax with promise, read interface data and output interface address:https://api.apiopen.top/getJoke

<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Document</title>
<! — introduce the style of bootstrap — >
<link rel=”stylesheet” href=”https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.css”>
</head>
<body>
<div class=”container”>
< H2 class = “page header” > promise encapsulates Ajax operations</h2>
< button class = BTN BTN primary “id = BTN > > click send Ajax < / button > to send
</div>
<script>

const btn = document.querySelector(‘#btn’)
btn.onclick = function () {
const p = new Promise((resolve, reject) => {
xhr = new XMLHttpRequest()
xhr.open(‘GET’, ‘https://api.apiopen.top/getJoke‘)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
p.then(value => {
console.log(value);
}, reason => {
console.warn(reason);
})

}
</script>
</body>
</html>

3、 How to use promise?

Before we know how to use promise, let’s take a look at the two properties of promise instance objects:“Promise state” and “promise result”

3.1 status of promise

Each instance object has a property called「PromiseState」, this attribute has three values:

  • pending “Undecided”
  • resolved / fullfilled “Success”
  • rejected “Failure”

Change of state

  1. Pending becomes resolved
  2. Pending becomes rejected

Note: there are only two, and oneThe promise object can only be changed onceAfter the change, it cannot be modified. Whether it becomes a success or a failure, there will be a result data. The successful result data is generally called value, and the failed result data is generally called reason

3.2 results of promise

Each instance object has a property called「PromiseResult」, which is used to save instance objects (asynchronous tasks)“Success or failure”The result of the test.

onlyresolveandrejectYou can modify the value of this property.

4、 API of promise

4.1 resolve method

If the passed in parameter is a non promise type object, the returned result is a successful promise object. If the passed in parameter is a promise object, the result of the parameter determines the result of resolve

const p1 = Promise.resolve(520)
console.log(p1); // PromiseState => fulfilled

const p2 = Promise.resolve(new Promise((resolve, reject) => {
reject(‘111’)
}))

//There is a failed callback inside, but it is not processed. Therefore, an error will be reported
console.log (P2); / / projectstate = > rejected: uncaught (in project) 111

p2.catch(reason => {
console.log(reason); // 111
})

4.2 reject method

Always returns a rejected “failed” project object.

// const p = Promise.reject(521)
//Note that an error will be reported here because there is a failed promise inside, but there is no corresponding callback to handle it
// console.log(p); // PromiseState rejected

const p2 = Promise.reject(new Promise((resolve, reject) => {
resolve(‘123’)
}))
console.log(p2); // PromiseState rejected
p2.then(value =>{
console.log(value);
},reason =>{
console.log (reason); / / the result of failure is a promise object whose status is success
})

4.3 methods

Grammar:

Promise.all (array) / / array a set of promise objects
1

Note: return a new promise, only if all the promises are successful, as long as one fails, it will fail directly

In the first case, it’s all resolved:

const p1 = new Promise((resolve, reject) => {
resolve(‘ok’)
})
const p2 = Promise.resolve(‘success’)
const p3 = Promise.resolve(‘Oh Yeah’)

const result = Promise.all([p1, p2, p3])

console.log(‘result: ‘, result);
// PromiseState “fulfilled”
// PromiseResult [‘ok’,’success’,’Oh Yeah’]

In the second case, there is a rejected:

const p1 = new Promise((resolve, reject) => {
resolve(‘ok’)
})
const p2 = Promise.reject(‘error info’)
const p3 = Promise.resolve(‘Oh Yeah’)

const result = Promise.all([p1, p2, p3])

console.log(‘result: ‘, result);
// PromiseState “rejected”
// PromiseResult “error info”

4.4 race method

The race function returns a project, which can be either resolved or rejected, depending on which one is completed first.

In the first case, what should be done first is「P1 => resolved」 :

const p1 = new Promise((resolve, reject) => {
resolve(‘ok’)
})
const p2 = Promise.reject(‘error’)
const p3 = Promise.resolve(‘Oh Yeah’)

const result = Promise.race([p1, p2, p3])
console.log(result); // PromiseState:”fulfilled” PromiseResult:”ok”

In the second case, what should be done first is「P2 => rejected」:

//First clock test mode:
//Note: the position of the race method parameter is changed here
const p1 = new Promise((resolve, reject) => {
resolve(‘ok’)
})
const p2 = Promise.reject(‘error info’)
const p3 = Promise.resolve(‘Oh Yeah’)

const result = Promise.race([p2, p1, p3])
console.log(result); // PromiseState:”rejected” PromiseResult:”error info”

//Second clock test mode:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘ok’)
}, 1000);
})
const p2 = Promise.reject(‘error info’)
const p3 = Promise.resolve(‘Oh Yeah’)

const result = Promise.race([p1, p2, p3])
console.log(result); // PromiseState:”rejected” PromiseResult:”error info”

4.5 then method of instance object

The then method has a return value, which is a promise object. The state is determined by the execution result of the callback function

  1. The return result is not primose type, the status is success, the return value is the return value in the then method (123 in the example below is the return value), if there is no return in the method, it is undefined
  2. If the return value is a promise object, the state and value returned by the internal promise object determine the state and value of the external then method
  3. If an error is thrown, the then method state is rejected and the value is the value thrown

Tip: as like as two peas returned by async, the return value of the then method is exactly the same.

const p = new Promise((resolve, reject) => {
resolve(‘ok’)
})

const result = p.then(value => {
//1. Return the normal data status as success, no return status as success, and the value is undefined
// return 123;

//2. Throw an error, the status is failed, and the value is the thrown value
//Throw ‘wrong’

//3. Return a promise. The internal promise determines the status and return value of the external then method
return new Promise((resolve, reject) => {
// resolve()
// reject()
Throw ‘wrong’;
})
}, err => {
console.error(err);
})
console.log (result); / / projectstate: “rejected” projectresult: “error!”

exceptional case:

The expected parameter of then method is a function. If it is not a function, promise penetration (value penetration) will occur. The state is the state of the previous promise and the value is the value of the previous promise.

//Special cases:
const p = new Promise((resolve, reject) => {
resolve(‘ok’)
// reject(‘error’)
})
const result = p.then(console.log(123))
console.log(result); // PromiseState: “fulfilled” PromiseResult: “ok”
1234567

A little more difficult:

Promise.resolve(‘foo’)
.then(Promise.resolve(‘bar’))
.then(function(result){
console.log(result)
})

Of course, the output is foo. The answer is as follows: promise value penetration explanation: the parameter of. Then or. Catch is expected to be a function, and the value penetration will occur if a non function is passed in.

One more way:

Promise.resolve(1)
.then(function(){return 2})
.then(Promise.resolve(3))
.then(console.log)

Output: 2 explanation: Promise.resolve (3) It’s not a function. It’s a value penetration

Continue:

Promise.resolve(1)
.then(function(){return 2})
.then(function(){return Promise.resolve(3)})
.then(console.log)

output:3

5、 Async and await

5.1 async

The return value of the function modified with async keyword is always promise object. The state of this prmose object and the state of the return value of the then method are the same rules applied.

A simple example:

async function main(){

}
let result = main()
console.log(result); // “fulfilled” “undefined”

5.2 await

The expression on the right side of await is generally a promise object, but it can also be something else

  1. If there is no promise on the right side: take this value as the return value of await directly
  2. On the right is the successful promise: the value of promise success is returned
  3. On the right is the failed promise: throw an exception, which needs to be handled by try catch

Note: await must be written in async function, but there can be no await in async function

async function main() {
//1. There is no promise on the right side: take this value as the return value of await directly
let result = await ‘str’
console.log(result); // result => str info => fulfilled str
return result

//2. The right side is the successful promise: the value of promise success is returned
// let p1 = new Promise((resolve, reject) => {
//   resolve(‘ok’)
// })
// let result1 = await p1
// console.log(result1); // result => ok info => fulfilled ok
// return result1

//3. On the right side is the failed promise: an exception is thrown, which needs to be captured by try catch
// let p2 = new Promise((resolve, reject) => {
//   reject(‘error’)
// })
// try {
//   let result2 = await p2
// } catch (e) {
//   console.log(e); // e => error info => fulfilled error
//   return e
// }
}
const info = main()
console.log(info);

6、 Sending Ajax with async and await

<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Document</title>
<! — introduce the style of bootstrap — >
<link rel=”stylesheet” href=”https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.css”>
</head>

<body>
<div class=”container”>
Encapsulating Ajax operations with async and await</h2>
< button class = BTN BTN primary “id = BTN > > click send Ajax < / button > to send
</div>
<script>
function sendAJAX(url) {
return new Promise((resolve, reject) => {
xhr = new XMLHttpRequest()
xhr.responseType = ‘json’
xhr.open(‘GET’, url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
}

const btn = document.querySelector(‘#btn’)
btn.addEventListener(‘click’, async function () {
let result = await sendAJAX(‘https://api.apiopen.top/getJoke‘)
console.log(result);
})
</script>
</body>
</html>

Recommended Today

How does git store data

How does git store data Git is one of the tools that we use most every day. It is a new version control tool created by Linus Torvalds, the earliest author of Linux kernel. It is as simple and easy to use as Linux. This article will briefly talk about how git works requirement I […]