首页 > 解决方案 > 什么时候应该使用 JavaScript 中的回调函数

问题描述

有人可以解释一下我们应该如何知道何时应该使用回调?就像这里给出的代码一样,这里给出了代码的链接 片段, 我们看到在readFile方法里面fetchAll(cb),我们使用callback表示(cb)来读取内容,parse它和stringify它等等,但是在readFile方法中save(),没有必要使用(cb)。那么我们怎么知道什么时候使用回调呢?

标签: node.js

解决方案


const fs=require('fs')
const path=require('path')
module.exports=class Prroduct{
constructor(title,imgurl,description,price){
this.title=title
this.imgurl=imgurl
this.description=description
this.price=price
}
save(){
const p=path.join(__dirname,'../','data','products.json')
fs.readFile(p,(err,fileContent)=>{
let products=[]
if(!err){
products=JSON.parse(fileContent)
}   
products.push(this)
fs.writeFile(p,JSON.stringify(products),(err)=>{
console.log(err)
})
}) 
}
static fetchAll(cb){
const p=path.join(__dirname,'../','data','products.json')
fs.readFile(p,(err,fileContent)=>{
if(err){
         cb([])
     }
    cb(JSON.parse(fileContent))
})
}
}

推荐阅读