1

I have an array of objects (books) that are missing some fields, so I'm using node-isbn module to fetch the missing data. However, I'm having trouble persisting the updates to the objects. Here's some example code:

const isbn = require('node-isbn');

var books = []; // assume this is filled in elsewhere

books.forEach(function(item) {
    if (item.publication_year == '' ||
        item.num_pages == '') {
        isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn)
            .then(function (book) {
                item.num_pages = book.pageCount;
                item.publication_year = book.publishedDate.replace( /^\D+/g, '');
            }).catch(function (err) {
                console.log('Book not found', err);
            });
    }
    console.log(item)
});

However, the console log shows that the num_pages and publication_year fields are still empty. How can I fix this?

andrei
  • 2,053
  • 3
  • 17
  • 16

2 Answers2

1

Try not to use Promise inside forEach

1

Put your console.log inside the then block , it will print the result for you.You are doing a asynchronous operation by resolving promise so it will take some time for the data to come back , however since your console.log is outside of that promise , that will get executed first.

So if you want to see those values, you should put your console.log inside your then block.

However, You can use await and for of syntax to achieve the result

for await (item of books) {

  if (item.publication_year == '' || item.num_pages == '') {
         const book = await isbn.provider(['openlibrary', 'google'])
            .resolve(item.isbn);

         item.num_pages = book.pageCount;
         item.publication_year = book.publishedDate.replace( /^\D+/g,'');

    }
    console.log(item)
}

console.log(books)
Shijil Narayanan
  • 1,011
  • 8
  • 21
  • Sure, I can do that. The end goal though, is to use the modified array of items (save to disk, etc), so how can I do that after the loop ends? – andrei May 30 '20 at 04:55
  • Seems like my version of node doesn't like the "await" keyword. I get "SyntaxError: Unexpected reserved word". Using version 14.3.0. – andrei Jun 01 '20 at 03:17