淘先锋技术网

首页 1 2 3 4 5 6 7

promise初级用法

const testPath = path.join(__dirname, 'test.txt')

const readFileAsync = new Promise((resolve, reject) => {
  const data = readFile(testPath, 'utf8', (data, err) => {
    if (data) resolve(data)
    else reject(err)
  })
})

readFileAsync.then((data) => {
  console.log(data)
}, (err) => {
  console.log(err)
})

这段代码中readFileAsync.then()会立即执行


包装高阶函数, 让异步函数可以传递参数

const testPath = path.join(__dirname, 'test.txt')

const readFileAsync = (path) => {
  return new Promise((resolve, reject) => {
    readFile(path, 'utf8', (data, err) => {
      if (data) resolve(data)
      else reject(err)
    })
  })
}

readFileAsync(testPath).then((data) => {
  console.log(data)
}, (err) => {
  console.log(err)
})

通过async-await函数使用:

;(async () => {
  try {
    const data = await readFileAsync(testPath)
    console.log(data)
  } catch (err) {
    console.log(err)
  }
})()


setTimeout延迟执行

const sleep = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time)
  })
}

sleep().then(()=>{console.log('过了两秒钟打印');})
// 或者通过这种方法
;(async () => {
  await sleep()
  console.log('run in 2s')
})()