promise到async

const fs=require('fs');
const path=require('path');

const p1=new Promise(function(reslove,reject){
  fs.readFile(path.join(__dirname,'data','data.json'),'utf-8',function(err,data){
     if(err){
      reject(err)
      return
     }
     reslove(data)
  })
})
const p2=new Promise(function(reslove,reject){
  fs.readFile(path.join(__dirname,'data','data1.json'),'utf-8',function(err,data){
     if(err){
      reject(err)
      return
     }
     reslove(data)
  })
})
const p3=new Promise(function(reslove,reject){
  fs.readFile(path.join(__dirname,'data','data2.json'),'utf-8',function(err,data){
     if(err){
      reject(err)
      return
     }
     reslove(data)
  })
})

注:Generator是 promise的语法糖

promise

p1.then(res=>{
  console.log(res)
  return p2
}).then(res=>{
  console.log(res)
   return p3
}).then(res=>{
  console.log(res)
  
})

Generator 函数

/* Generator 函数前面要加**/
function * fn(){
   yield p1
   yield p2
   yield p3
}
let g=fn()
g.next().value.then(res=>{
  console.log(res)
  return g.next().value
}).then(res=>{
  console.log(res)
  return g.next().value
}).then(res=>{
  console.log(res)
  return g.next().value
})

co

//引入co
const co=require('co');

co(function * (){
  let a=yield p1
  let b=yield p2
  let c=yield p3
  console.log(a)
  console.log(b)
  console.log(c)
})

async await

async function fn(){
  let a=await p1
  let b=await p2
  let c=await p3
  console.log(a)
  console.log(b)
  console.log(c)
}
fn()

 

 

 

你可能感兴趣的:(js)