promise 获取文件内容

文件结构图

{
    "next":"b.json",
     "msg":"this is a"
}
a.json
{
    "next":"c.json",
     "msg":"this is b"
}
b.json
{
    "next":"null",
     "msg":"this is c"
}
c.json

 

上一层

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


//用jpromise获取文件内容

function getFileContent(filName){

      const  promise= new Promise((resolve, reject)=>{
         
        const fullFileName=path.resolve(__dirname,'files',filName)

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

              if(err){
                  reject(err)
                  return
              }
              resolve(
                  JSON.parse(data.toString())
                  )
         })
            
      })
      return promise
}

getFileContent('a.json').then(aData=>{
     console.log("a data", aData)
     return getFileContent(aData.next)
}).then(bData=>{
    console.log("b data", bData)
    return getFileContent(bData.next)
}).then(cData=>{
    console.log("c data", cData)
})

 

posted @ 2019-12-06 11:45  distant-遥远  阅读(487)  评论(0编辑  收藏  举报