js async04

Posted anch

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js async04相关的知识,希望对你有一定的参考价值。

function resolveAfter2Seconds() {
  console.log(‘slow start at: ‘ + new Date().getSeconds())
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(‘slow‘)
      console.log(‘slow done at: ‘ + new Date().getSeconds())
    }, 2000 )
  })
}
function resolveAfter1Second() {
  console.log(‘fast start at: ‘ + new Date().getSeconds())
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(‘fast‘)
      console.log(‘fast done at: ‘ + new Date().getSeconds())
    }, 1000 )
  })
}
const concurrentPromise = function() {
  console.log(‘CONSURRENT START WITH promise at: ‘ + new Date().getSeconds())
  return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then(messages => {
    console.log(messages[0] + ‘ at: ‘ + new Date().getSeconds()) 
    console.log(messages[1] + ‘ at: ‘ + new Date().getSeconds())
  })
}
concurrentPromise()

//

CONSURRENT START WITH promise at: 42
slow start at: 42
fast start at: 42
fast done at: 43
slow done at: 44
slow at: 44
fast at: 44

以上是关于js async04的主要内容,如果未能解决你的问题,请参考以下文章

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

js async04

node.js async.js nextTick vs setImmediate

node.js async.js nextTick vs setImmediate

async/await 不适用于 ComponentDidMount 中的 react.js

Node.js JavaScript 片段中的跳过代码