这是一个图书捐赠项目,我正在尝试以 async / await 的方式编写一些方法。
BooksRepo:具有所有方法的类
class BooksRepo {
constructor() {
this.fse = require('fs-extra');
this.catalogFilePath = '../data/catalog.books.json';
}
async readFileAsync(filePath) {
let data = await this.fse.readFile(filePath);
let parsedData = await JSON.parse(data);
return parsedData;
}
async getBook(bookName) {
let books = await this.readFileAsync(this.catalogFilePath);
let book = books.find(b => b.title == bookName);
return book;
}
}
目录文件:结构示例
[
{
"_id": 1,
"title": "Unlocking Android",
"isbn": "1933988673",
"pageCount": 416,
"publishedDate": {
"$date": "2009-04-01T00:00:00.000-0700"
},
"thumbnailUrl": "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/ableson.jpg",
"shortDescription": "Unlocking Android: A Developer's Guide provides concise...",
"longDescription": "Android is an open source mobile phone platform based on the Linux operating ...",
"status": "PUBLISH",
"authors": [
"W. Frank Ableson",
"Charlie Collins",
"Robi Sen"
],
"categories": [
"Open Source",
"Mobile"
]
},
app:类,这就是我试图调用方法的方式
let booksRepo = new BooksRepo();
booksRepo.readFileAsync(booksRepo.catalogFilePath).then(result=> console.log(result));
let books = booksRepo.getBook("Android in Action, Second Edition");
console.log(books)
我收到此错误 未定义BooksRepo
我不知道问题出在哪里
答案 0 :(得分:0)
您似乎对进出口有问题。
首先,您必须将类导出到其所在的文件中:
module.exports = BooksRepo;
然后将其导入使用的文件中:
var BooksRepo = require('./books-repo');
或者:
export default class BooksRepo { ...
和
import BooksRepo from './books-repo.js';