【问题标题】:Modify external object in promise function在 promise 函数中修改外部对象
【发布时间】:2020-09-17 17:19:12
【问题描述】:

我有一个缺少某些字段的对象(书籍)数组,因此我使用node-isbn 模块来获取丢失的数据。但是,我无法持久保存对象的更新。下面是一些示例代码:

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

但是,控制台日志显示 num_pagespublication_year 字段仍然为空。我该如何解决这个问题?

【问题讨论】:

  • 似乎正确.. 只有你在异步返回之前登录控制台

标签: javascript node.js


【解决方案1】:

尽量不要在 forEach 中使用 Promise

【讨论】:

  • 那么更新数组中的项目的正确方法是什么?
  • 您可以将它们中的每一个映射到一组承诺中,然后使用 Promiss.all 来执行它
【解决方案2】:

将您的 console.log 放在 then 块中,它会为您打印结果。您正在通过解析 promise 进行异步操作,因此数据需要一些时间才能返回,但是由于您的 console.log 是在该承诺之外,它将首先执行。

因此,如果您想查看这些值,则应将 console.log 放在 then 块中。

但是,您可以使用awaitfor of 语法来实现结果

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)

【讨论】:

  • 当然可以。不过,最终目标是使用修改后的项目数组(保存到磁盘等),那么在循环结束后我该怎么做呢?
  • 似乎我的节点版本不喜欢“等待”关键字。我得到“语法错误:意外的保留字”。使用版本 14.3.0。
猜你喜欢
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
相关资源
最近更新 更多