New spices, new flavors

This article is based on the interview questions. It is not recommended to apply to the project

The basic concept

Promise

The agent, which holds a value for future use, is itself executed strictly asynchronously

function resolveUnderThreeSeconds(delay) {
  return new Promise(function(resolve, reject) {
    setTimeout((a)= > resolve('success'), delay)
    setTimeout((a)= > reject('fail'), 3000)
  })
}

resolveUnderThreeSeconds(2000)
  .then(res= > {
    console.log('res', res)
  })
  .catch(err= > {
    console.log('err', err)
  })
Copy the code

When writing asynchronous code, it is possible that one of two tasks will depend on the results of the other, so the two tasks must be executed sequentially

The promise.all () method takes an array of promises and returns the result data of each Promise in the order in which it was passed. If one of the promises is rejected, it pauses and returns an error message

const p1 = Promise.reject('failed')
const p2 = Promise.resolve('success')
const p3 = Promise.resolve('success')
const p = Promise.all([p1, p2, p3]).catch(err= > console.log(err))
Copy the code

Async/Await

Async functions combine Promise – based implementations with generator-style synchronous writing

function resolveAfter2Seconds() {
  return new Promise(resolve= > {
    setTimeout((a)= > {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

Copy the code

implementation

Functional analysis

Key: promise.all () passes in an array of promises. After all the promises in the array are successfully executed, the result data of each Promise will be returned according to the incoming order. If one Promise is rejected, it will be suspended and return an error message

An array goes into an async function, loops through async/await the incoming array function, then forms an array with the result of the function, and returns the array

Try /catch can get any await error in async function, and if one of them is rejected, it will pause and return an error message

async function asyncAlls(jobs) {
  try {
    // Execute the loop
    let results = jobs.map(async job => await job)
    let res = []
    // Combine arrays
    for (const result of results) {
      res.push(await result)
    }
    return res
  } catch (error) {
    throw new Error(error)
  }
}
Copy the code

Examples show


function doJob(x, sec) {
  if(! x) {throw new Error('test error')}return new Promise(resolve= > {
    console.log('Start: ' + x)
    setTimeout((a)= > {
      console.log('End: ' + x)
      resolve(x)
    }, sec * 100)})}async function asyncAlls(jobs) {
  try {
    let results = jobs.map(async job => await job)
    let res = []
    for (const result of results) {
      res.push(await result)
    }
    return res
  } catch (error) {
    throw new Error(error)
  }
}
(async function() {
  try {
    const all1 = await asyncAlls([doJob(1.1), doJob(2.1), doJob(0.1), doJob(4.1)])
    console.log('all1', all1)
  } catch (error) {
    console.log('0', error)
  }
  try {
    const all2 = await asyncAlls([doJob(5.1), doJob(6.1), doJob(7.1), doJob(8.1)])
    console.log('all2', all2)
  } catch (error) {
    console.log('1', error)
  }
})()


Copy the code

conclusion

This article is based on an interview question. Due to curiosity, I spent some time to realize it. During this period, I also consulted many partners about many things I don’t understand

The examples in this article are for study only, and are not recommended for practical application

Thank you for reading


reference

  • JavaScript Async/Await: Serial, Parallel and Complex Flow
  • Let’s talk about Async

Read the original