洋葱模型

  1. // await 将中间件函数切割了 只有next中的函数执行完毕之后,上一段中函数await后面的被入
  2. // 洋葱模型
  1. /* async await */
  2. /*
  3. promise函数执行
  4. 1、then
  5. 2、在async函数中,通过await语句去执行
  6. */
  7. 在函数前面加上async
  8. 1.这个函数的返回值就是promise
  9. 2.可以在函数中使用await关键字
  1. var a = new Promise((resolve,reject)=>{
  2. setTimeout(()=>{
  3. resolve(1)
  4. },2000)
  5. })
  6. var b = new Promise((resolve,reject)=>{
  7. setTimeout(()=>{
  8. resolve(2)
  9. },1000)
  10. })
  11. async function go(){
  12. var res = await a;
  13. console.log(res);
  14. var sum = await b;
  15. console.log(sum);
  16. }
  17. go()
  1. 以鸡蛋 蛋壳 蛋白为例
  1. app.use(async(ctx,next)=>{
  2. console.log("蛋壳-->左");
  3. await next()
  4. console.log("蛋壳-->右");
  5. app.use(async (ctx,next)=>{
  6. console.log("蛋白-->左");
  7. await next()
  8. console.log("蛋白-->右");
  9. // console.log(3);
  10. // return "2"
  11. })
  12. app.use(async (ctx)=>{
  13. console.log("蛋黄");
  14. })
  15. 蛋壳-->左
  16. 蛋白-->左
  17. 蛋黄
  18. 蛋壳-->右
  19. 蛋白-->右