promise避免回调地狱

回调函数:

const fs=require(‘fs’)

const  path =require('path')

function getFileContent(filename,callback){

const fullFileName=path.resolve(__dirname,'files', )//__dirname当前文件的目录,files文件夹名称

fs.readFile(fullFileName,(err,date)=>{

if(err){

console.error(err)

return

}

callback(JSON.parse(date.tostring()))

})

}

getFileContent('a.json',aDate=>{

console.log('a.date',aDate)

getFileContent(aDate.next,bData=>{

}')//读取a.jaon中的内容后传给下一次调用的函数的参数,

})

promise方式:

function getFileContent(fileName){

const promise=new Promise((resolve,reject)=>{

const fullFileName=path.resolve(__dirname,'files', )//__dirname当前文件的目录,files文件夹名称

fs.readFile(fullFileName,(err,date)=>{

if(err){

reject(err)

return

}

resolve(JSON.parse(data.tostring()))

})

})

return promise

}

getFileContent('a.json').then(aData=>{

console.log('adata',aData)

return getFileContent(aData.next)

}).then(bdata=>{

console.log('bdata',bData)

})

猜你喜欢

转载自www.cnblogs.com/wujianmin-web/p/10703560.html