JavaScript - async/await 基础示例

一个函数如果被 async 修饰,无论内部是否有 await的异步操作,都会返回一个 Promise 对象

demo 1

async function basicAsync() {
  let result = await (Math.random() * 200).toFixed(2)
  console.info(result) // ===>>>> 47.22
  return result
}
// 直接调用async方法,返回一个promise,可以使用.then()来解析promise返回结果
const p = basicAsync()
console.info(p) // ===>>>> 返回 Promise {<pending>}
p.then(res => {
  console.info(res) // ===>>>> 47.22
})

demo 2

async function basicAsync() {
  return 'hello async'
}
const p = basicAsync()
console.info(p) // =====>>>> 返回 Promise {<resolved>: "hello async"}




posted @ 2020-07-21 09:15  荣光无限  阅读(301)  评论(0编辑  收藏  举报