node.js - 什么时候应该使用 JavaScript 中的回调函数
问题描述
有人可以解释一下我们应该如何知道何时应该使用回调?就像这里给出的代码一样,这里给出了代码的链接
片段,
我们看到在readFile
方法里面fetchAll(cb)
,我们使用callback
表示(cb)
来读取内容,parse
它和stringify
它等等,但是在readFile
方法中save()
,没有必要使用(cb)
。那么我们怎么知道什么时候使用回调呢?
解决方案
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))
})
}
}
推荐阅读
- python - 在一个 Python 会话中调查不同版本的 Python 包
- python - 通过pyodbc访问全局临时表
- python - 如何在 Python 中使用 lxml 从 html 中提取除 css 和 javascript 之外的所有文本?
- arrays - 如何在delphi中对数组进行“序列化”和“反序列化”?
- php - 带有类别/子类别名称的产品列表
- svg - SVG - 如何放大每个单词所在的字体大小
标签和每个字母都在里面 标签? - c# - WPF 在 wpf dll 中使用 ViewModelLocator
- go - cgo 不导出导入包中的函数
- python - Python Quicksort函数进入无限循环
- python - 如何展平多个级别的元组并具有制表符分隔的元素?