Click the top “IT teamhead alliance” and select “Top or star label”.

Grow with you ~

instructions

Recently, I reviewed Promise’s knowledge. I saw some interesting questions. Here are some questions.

Subject to a

const promise = new Promise((resolve, reject) => { console.log(1); resolve(); console.log(2); })promise.then(() => { console.log(3); })console.log(4);Copy the code

First, the Promise is executed immediately after it is created, so 1,2 is printed first, while the code inside promise.then () is executed immediately at the end of the next event loop, so 4 is continued and 3 is printed. The answer

1243Copy the code

Topic 2

const promise = new Promise((resolve, reject) => { resolve('success1'); reject('error'); resolve('success2'); }); promise.then((res) => { console.log('then:', res); }).catch((err) => { console.log('catch:', err); })Copy the code

Resolve changes the state of the Promise object from “unfinished” to “successful” (that is, from pending to Resolved), calls it when the asynchronous operation succeeds, and passes the result of the asynchronous operation as a parameter.

The Reject function changes the state of the Promise object from “unfinished” to “failed” (that is, from pending to Rejected), calls it when the asynchronous operation fails, and passes the error reported by the asynchronous operation as an argument.

And once the state changes, it never changes. So the code reject(‘error’); It won’t work.

A Promise can only be resolved once, and any other calls are ignored. So the second resolve(‘success2’); It’s not going to work.

The answer

then: success1Copy the code

The title three

Promise.resolve(1)  .then(2)  .then(Promise.resolve(3))  .then(console.log)Copy the code

parsing

The Promise. Resolve method returns a new Promise object in the resolved state, if the parameter is a raw value or an object that does not have then methods. The arguments to the promise. resolve method are also passed to the callback function.

The then method takes a function as an argument, and if it passes something other than a function, it actually interprets it as THEN (NULL), which causes the result of the previous Promise to penetrate below.

The answer

1Copy the code

The title four

The red light is on once in three seconds, the green light is on once in one second, and the yellow light is on once in two seconds; How do I make three lights turn on again and again? Three lighting functions already exist (implemented with Promse) :

function red() { console.log('red'); }function green() { console.log('green'); }function yellow() { console.log('yellow'); }Copy the code

parsing

Three seconds on a red light, green light for a second time, yellow light 2 seconds on time, which means that for 3 seconds, performs a function of red, 2 seconds, perform a green function, 1 second to perform a yellow function, alternating repeated lights, which means that in this order has been executed this three functions, this step can use recursion to achieve.

The answer

function red() { console.log('red'); }function green() { console.log('green'); }function yellow() { console.log('yellow'); }var light = function (timmer, cb) { return new Promise(function (resolve, reject) { setTimeout(function () { cb(); resolve(); }, timmer); }); }; var step = function () { Promise.resolve().then(function () { return light(3000, red); }).then(function () { return light(2000, green); }).then(function () { return light(1000, yellow); }).then(function () { step(); }); }step();Copy the code

Topic five

Implement the mergePromise function, which executes the array passed in in sequence, and places the returned data in the array data in sequence.

const timeout = ms => new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, ms); }); const ajax1 = () => timeout(2000).then(() => { console.log('1'); return 1; }); const ajax2 = () => timeout(1000).then(() => { console.log('2'); return 2; }); const ajax3 = () => timeout(2000).then(() => { console.log('3'); return 3; }); Const mergePromise = ajaxArray => {// Implement your code here}; mergePromise([ajax1, ajax2, ajax3]).then(data => { console.log('done'); console.log(data); // data is [1, 2, 3]}); [1, 2, 3] [1, 2, 3]Copy the code

parsing

Ajax1, ajax2, and ajax3 are all functions, but they return a Promise when executed. We just execute them sequentially and put the result in data, but these functions are all asynchronous and want to execute them sequentially, and then print 1,2, 3 is not that simple. Let’s see.

function A() { setTimeout(function () { console.log('a'); }, 3000); }function B() { setTimeout(function () { console.log('b'); }, 1000); }A(); B(); // b// aCopy the code

In the example, we execute A sequentially, B but the output is B, A for these asynchronous functions, it does not execute one sequentially and then the next. So we’re going to use Promise to control asynchronous flow, and we’re going to have to figure out how to make one of these functions execute, and then execute the next one. Let’s see.

The answer

Var data = []; The resolve method is called with no arguments and returns an Resolved Promise object. var sequence = Promise.resolve(); Ajaxarray. forEach(function (item) {// The first then method executes each function in the array, and the second then method takes the result of each function in the array, and adds the result to the data, And then return the data. sequence = sequence.then(item).then(function (res) { data.push(res); return data; }); })// After the loop is complete, return a Promise, i.e., a sequence, whose [[PromiseValue]] value is data, which is passed as a parameter to the next call to the then method. return sequence;Copy the code

Topic 6

What does the following code output?

const first = () => (new Promise((resolve, reject) => { console.log(3); let p = new Promise((resolve, reject) => { console.log(7); setTimeout(() => { console.log(5); resolve(6); }, 0) resolve(1); }); resolve(2); p.then((arg) => { console.log(arg); }); })); first().then((arg) => { console.log(arg); }); console.log(4);Copy the code

In fact, the analysis of this problem is not much related to Promise, mainly need to understand the JS execution mechanism, in order to solve this problem well

The first event loop

First execute the macro task, the main script, new Promise immediately execute, print [3], execute the new Promise operation p, print [7], find setTimeout, put the callback into the next task Queue (Event Queue), p then, Let’s call it then1 and put it on the microtask queue, and then that finds first, let’s call it then2 and put it on the microtask queue. Execute console.log(4), output [4], and the macro task is finished. Then execute the micro task, execute then1, output [1], execute then2, output [2]. This is the end of the first event loop. Start the second round.

The second event loop first executes the callback of setTimeout in the macro task, and outputs [5]. Resolve (6) will not take effect, because once the state of p changes, it will not change again.

The answer

374125 Copy the code

Title seven

There are eight image resource urls already stored in an array of urls (i.e. Urls = [‘http://example.com/1.jpg’,… ., ‘http://example.com/8.jpg’]), and there is already a function called function loadImg that enters a URL link and returns a Promise to resolve when the image download is complete. Download fail reject. However, we require that no more than three links be downloaded at any one time. Write a piece of code to implement this requirement, requiring all images to be downloaded as quickly as possible.

var urls = ['https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg', 'https://www.kkkk1000.com/images/getImgData/gray.gif', 'https://www.kkkk1000.com/images/getImgData/Particle.gif', 'https://www.kkkk1000.com/images/getImgData/arithmetic.png', 'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif', 'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg', 'https://www.kkkk1000.com/images/getImgData/arithmetic.gif', 'https://www.kkkk1000.com/images/wxQrCode2.png']; function loadImg(url) { return new Promise((resolve, Reject) => {const img = new Image() img.onload = function () {console.log(' a new Image is loaded '); resolve(); } img.onerror = reject img.src = url })};Copy the code

When one image is loaded, we will continue to request another image, keeping the number of concurrent requests at 3, until all images to be loaded have been requested.

Promises are an array of promises. Call promises. Race repeatedly to return promises that change their state the fastest. Then delete promises from the array (Promises) and add a new Promise until all urls are taken. Finally, use promise. all to make promises that have not changed state.

The answer

var urls = ['https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg', 'https://www.kkkk1000.com/images/getImgData/gray.gif', 'https://www.kkkk1000.com/images/getImgData/Particle.gif', 'https://www.kkkk1000.com/images/getImgData/arithmetic.png', 'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif', 'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg', 'https://www.kkkk1000.com/images/getImgData/arithmetic.gif', 'https://www.kkkk1000.com/images/wxQrCode2.png']; function loadImg(url) { return new Promise((resolve, Reject) => {const img = new Image() img.onload = function () {console.log(' a new Image is loaded '); resolve(); } img.onerror = reject img.src = url })}; Function limitLoad(urls, handler, limit) {// Make a copy of array const sequence = []. Concat (urls) let promises = []; // Promise = sequence.splice(0, limit).map((url, index) => { Return handler(URL).then(() => {return index}); }); Return sequence.reduce((last, url, Return promise.race (promises)}). Catch (err => {// here Catch is used not only to catch errors thrown by previous THEN methods // but more importantly to prevent the entire chain from being interrupted by the call console.error(err)}). Then ((res) => {// Replace the Promise that changed the state the fastest with a new Promise promises[res] = handler(sequence[currentIndex]).then(() => { return res }); }) }, Promise.resolve()).then(() => { return Promise.all(promises) })}limitLoad(urls, loadImg, LimitLoad (urls, loadImg, 3). Then (() => {console.log(' All images are loaded '); }).catch(err => { console.error(err); }) * /Copy the code

conclusion

These questions, there is the examination of Promise basic knowledge, there is also the flexible use of Promise, if these questions you do very well, then your understanding of Promise should be good.

Article Source:

https://segmentfault.com/a/1190000016848192

– end –

Share with heart grow together to be the temperature of the siege lion

Every day remember to say to yourself: you are the best!

Recommended reading

Internet “winter”, see big factory HR how to say ~

Free access to a large number of learning resources

Have an in-depth understanding of the browser caching mechanism

E Ruda a forgotten debugger