This is the 13th day of my participation in the August More Text Challenge

This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation, it is important to clear the concept and clear implementation ideas, it is suggested to explain the concept first => write use cases => write pseudo-code => then realize specific functions, and then optimize, step by step.

26. Call asynchronous functions sequentially

What’s the problem

We often come across a page that calls several different interfaces, one in order. Here’s an example:

// Create a factory function that takes the name and asynchronous time
const promiseFactory = (name, wait, isFail = false) = > {
  return new Promise((resolve, reject) = > {
    // Asynchronous task (simulated with setTimeout)
    setTimeout(() = > {
      if(! isFail) { resolve(I was `${name}And I need${wait}Ms, successful ')}else {
        reject(I was `${name}And I need${wait}Ms, execution failed)
      }
    }, wait)
  })
}

let pro1 = promiseFactory('First asynchronous task'.3000)
let pro2 = promiseFactory('Second asynchronous task'.1000)
let pro3 = promiseFactory('Third asynchronous task'.2000)
let pro4 = promiseFactory('Fourth asynchronous task'.1500.true)

pro1.then(res= > console.log(res))
pro2.then(res= > console.log(res))
pro3.then(res= > console.log(res))
pro4.catch(err= > console.log(err))
Copy the code

The printed result is

  • I am the second asynchronous task, I need 1000 ms, execute successfully (print after 1000 ms)
  • I am the fourth asynchronous task, I need 1500 ms, fail (print after 1500 ms)
  • I am the third asynchronous task, I need 2000 ms, execute successfully (print after 2000 ms)
  • I am the first asynchronous task, I need 3000 ms, execute successfully (print after 3000 ms)

We can see that in this notation we are actually sorting and executing the print according to the return time of success or failure.

Analysis of the

So how do we do it by name, or call order

Promise.all

We might think of promise.all ()

A quick introduction to the promise.all () method

  • Receive an iterable object, such as Array, in which each member should theoretically be a Promise. If there are non-Promise items in the Array, this item is considered a success
  • If all promises succeed, an array of success results is returned
  • If one Promise fails, the failure result is returned

Let’s try it out. Notice the order of my arguments

Promise.all([pro1, pro3, pro2, 99]).then(res= > {
  console.log(res) 
}, err= > {
  console.log(err)
})
Copy the code

This is the success case, returns an array of success results

Output in 3 seconds

[' I'm the first asynchronous task and I need 3000 ms', 'I'm the second asynchronous task and I need 1000 ms',' I'm the third asynchronous task and I need 2000 ms', 99]Copy the code

The last item is a non-promise item, which is considered a success and returned directly

If one Promise fails, the failure result is returned

Promise.all([pro2, pro3, pro4]).then(res= > {
  console.log(res) 
}, err= > {
  console.log(err)
})
// I am the third asynchronous task, I need 1500 ms, execution failed
Copy the code

Then some people say, wrong and right want to go back together

Promise.allSettled

Let’s look at Promise.AllSettled ()

The promise.allSettled () method returns a Promise after all the given promises have fulfilled or rejected, with an array of objects, each representing the corresponding Promise result.

This is often used when you have multiple asynchronous tasks that don’t depend on each other to complete successfully, or when you always want to know the outcome of each promise.

Promise.all(), by contrast, is better suited to relying on each other or ending immediately in either reject. Look at the following example

Promise.allSettled([pro2, pro1, pro3, pro4]).then(res= > {
  console.log(res) 
}, err= > {
  console.log(err)
})

// Print the result[{status: "fulfilled".value: "I'm the second asynchronous task, I need 1000 ms, successful."},
  {status: "fulfilled".value: "I am the first asynchronous task, I need 3000 ms, successful execution."},
  {status: "fulfilled".value: "I am the third asynchronous task, I need 2000 ms, successful execution."},
  {status: "rejected".reason: "I'm the fourth asynchronous task, I need 1500 ms, failed."}]Copy the code

As you can see from the printout, success or failure is returned

async/await

We can also think of writing async/await asynchronously in a way that looks synchronous

async function asyncList () {
  const res1 = await promiseFactory('First asynchronous task'.3000)
  console.log(res1)
  const res2 = await promiseFactory('Second asynchronous task'.1000)
  console.log(res2)
  const res3 = await promiseFactory('Third asynchronous task'.2000)
  console.log(res3)
}

asyncList()
Copy the code

Print after 3 seconds:

I am the first asynchronous task, I need 3000 ms, successful execution in 1 second print: I am the second asynchronous task, I need 1000 ms, successful execution in 2 seconds print: I am the third asynchronous task, I need 2000 ms, successful executionCopy the code

It’s kind of a hassle to write this, but what if you have a lot of asynchronous tasks and you want to use loops?

forEach

So what happens if we try forEach

let proArr = [pro1, pro2, pro3]
proArr.forEach(async function(item) {
  let res = await item
  console.log(res)
})
Copy the code
  • Print after 1s: I am the second asynchronous task, I need 1000 ms, execute successfully
  • Print after 2s: I am the third asynchronous task, I need 2000 ms, execute successfully
  • Print after 3s: I am the first asynchronous task, I need 3000 ms, execute successfully

This is mainly because the concurrent execution of forEach is not sequential iteration as we imagined, so the 3 async/await async are independent and print according to the time of callback.

for await of

We also found a “for await of” in ES9

async function asyncFnList () {
  const proArr = [pro1, pro2, pro3]
  for await (let res of proArr) {
    console.log(res)
  }
}

asyncFnList()
Copy the code

Output at the same time after 3s

  • I am the first asynchronous task, I need 3000 ms, execute successfully
  • I am the second asynchronous task, I need 1000 ms, execute successfully
  • I am the third asynchronous task, I need 2000 ms, execute successfully

That’s fine.

In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference

  • Juejin. Cn/post / 699533…