简体   繁体   中英

Writing methods in async/await way

This is a Books Donation project and I am trying to write some methods in async/await way.

BooksRepo :class that has all the methods

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;
    }

}

catalogFile: Example of how it structured

[
  {
    "_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 : class this is how I am trying to call the methods

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)

I get this error BooksRepo is not defined

I don't know where is the problem

It looks you have a problem with exports/imports.

First, you have to export the class in the file it is in:

module.exports = BooksRepo;

Then to import it in the file where it's used:

var BooksRepo = require('./books-repo');

Alternatively:

export default class BooksRepo { ...

And

import BooksRepo from './books-repo.js';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM