几分钟搞会Promise,Async Await 实际应用

80 阅读2分钟

Promise 底层逻辑就是解决异步编程 异步变成同步

废话不多说直接上代码,假如我有三个函数分别打印 三段不同的内容

function one () {
 return 'i am one'
};

function two () {
 return 'i am two'
};

function three () {
 return 'i am three'
};

//然后咱们写一个函数调用这三个方法

function run () {
 console.log(one());
 console.log(two());
 console.log(three());
};

run()

以下是来自控制台的打印效果

image.png

然后我们设想一下 假如在实际开发中 我们需要在第二个函数内请求数据,可能服务器向我们返回数据需要一定的时间,所以我们加上一个 setTimeout

function one () {
 return 'i am one'
};

function two () {
 setTimeout (()=>{
  return 'i am two'
 },3000)
};

function three () {
 return 'i am three'
};

//然后咱们写一个函数调用 这三个方法

function run () {
 console.log(one());
 console.log(two());
 console.log(three());
};

run()

以下是控制台的打印结果 我们发现第二个函数是 undefined 所以这个时候就需要用到咱们的 promise了

image.png

function one () {
 return 'i am one'
};

function two () {
 return new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve('i am two')
  },3000)
 })
};

function three () {
 return 'i am three'
};

//然后咱们写一个函数调用 这三个方法

function run () {
 console.log(one());
 console.log(two());
 console.log(three());
};

run()

这个时候咱们发现控制台的输出内容变成了promise 接下来咱们的需求是 one two three 同步打印 就需要用到async await 先是控制台出现one 然后三秒后出现 two 和 three image.png

function one () {
 return 'i am one'
};

function two () {
 return new Promise((resolve,reject)=>{
  setTimeout(()=>{
    resolve('i am two')
  },3000)
 })
};

function three () {
 return 'i am three'
};

//然后咱们写一个函数调用 这三个方法

async function run () {
 console.log(one());
 console.log(await two());
 console.log(three());
};

run()

咱们只需要在run函数前加async 在two函数前加 await 就实现了目标功能

image.png

通过这个简单的案例咱们就能掌握promise的基本玩法