One of the difficulties in JavaScript ES6 is Promise. Today, I will sort out the relevant knowledge points. If you’re interviewing, that’s all you need to know, and no more.

I promise uses, basic promise and then

1. Promise is an object

2. The Promise object is used to indicate the eventual completion or failure of an asynchronous operation, and its resulting value.

3. Then is a property that is attached to the promise prototype chain.

4. Finally resolve, reject

Promise.prototype.then(onFulFilled, onRejected)
Copy the code

5. Because then returns a new Promise, it can be called chained.

Basic promise.then use

const pTest = function () { let randNum = Math.random(); Return new Promise((resolve, reject) => {setTimeout(() => {randNum > 0.5? resolve(randNum) : reject(randNum); }, 1000); }); } pTest().then( paramResolve => { console.log(`this is fulFilled, param is ${paramResolve}`); }, paramReject => { console.log(`this is reject, param is ${paramReject}`); });Copy the code

Second, the promise all

1. The code semantics are unknown when it is used to deal with multilevel intermodulation. The input iterable types are Array,Map, and Set. All resolve and Reject are processed in unison.

2. Return condition

The resolve to return:

2. There are no promisesCopy the code

Reject to return:

1. Any reject implemented by a promise returns 2. Enter an invalid promise. Reject returns the first reject messageCopy the code

3, how to use JS code to achieve

function all(iterable) { return new Promise((resolve, reject) => { let resolveArr = []; For (let key in iterable) {let item = iterable[key]; Promise if (typeof item === 'object' && typeof item.then === 'function') {item.then(resolveParam => {// Promise if (typeof item === 'object' && typeof item.then === 'function') {item.then(resolveParam => { ResolveArr [key] = resolveParam if (resolvear.length === iterable. Length) {resolve(resolveArr); }}, reject (reject), reject (reject); } else { resolveArr[key] = item; }}}); } all([ Promise.reject(123), // 1 Promise.resolve(456), // 2 new Promise((resolve, reject) => { setTimeout( () => { resolve(789) }, 5000); // 3 }) ]).then( resolveParam => { console.log(resolveParam); }).catch( err => { console.log(err); })Copy the code

Comment 1, return reject, output 123 to end comment 2. If comment 1 is run out, output 456,789 comment 3, which will be pending for 5 seconds

Fetch in React

Fetch is more efficient than XmlHttpRequest. It’s essentially a Promise. The first time, the header returns, and the second time, the data returns.

The fetch ('/file. TXT). Then (res = > {the console. The log (' network success); console.log(res); // let {ok} = res; // if(ok){// console.log(' accepted successfully '); //}else{// console.log(' accept failed '); Json () returns a Promise. Then (data => {// console.log(data); //}, err => {// console.log(' parsing failed '); / /}); return res.json(); //res.json is also a Promise}, err => {console.log(' network failed '); }).then(data => { console.log(data); }, err => {console.log(' parsing failed '); });Copy the code

Fourth, async – await

Async-await is a syntactic candy based on Promise. Many advanced programmers are not used to JS, so the purpose of this is to focus only on resolve and use catch to process reject

(async () => { try{ let res = await fetch('/public/exist.txt'); let {ok} = res; If (ok){console.log(' accepted successfully '); }else{console.log(' accept failed '); } // let data = await res.json(); // let data = await res.arrayBuffer(); let data = await res.text(); console.log(data); }catch(err){console.log(' failed '); }}) ();Copy the code

What formats can RES parse?

  • Json. Json and arrays
  • .arrayBuffer() A binary array
  • Blob binary large object: from a database, does not need to parse, used in multimedia files.
  • The text text.