如何通过异步调用来完成一系列信息?

时间:2018-10-27 15:59:13

标签: javascript node.js

我有以下代码可将一个人拥有的所有书籍的信息填充到数组中:

async getAllInfo(person_id)
{

    let book_list = await this.getBooks(person_id);

    for(let book in book_list)
    {
        book_list[book]["book_info"] = await this.getBookInfo(book_list[book]["book_id"])
    }

    return book_list;
}

当我运行getBooks时,我得到:

[
    {
        "name": "BookA",
        "book_id" : "123"
    },
    {
        "Name": "BookB",
        "book_id" : "456"
    }
]

然后我在for循环中完成有关这本书的信息:

[
    {
        "name": "BookA",
        "book_id" : "123",
        "book_info": {
            "author": "authorA",
            "publish_year": 1900
        }
    },
    {
        "name": "BookB",
        "book_id" : "456",
        "book_info": {
            "author": "authorB",
            "publish_year": 1900
        }
    }
]

getBooks和getBookInfo是http调用,当一个人拥有很多书时,可能需要一些时间来获取所有信息。是否可以同时获取数组中的所有书籍?我试图删除等待并使用Promise.all(),但我总是得到:

[
    {
        "name": "BookA",
        "book_id" : "123",
        "book_info": {
            "domain": {
                "domain": null,
                "_events": {},
                "_eventsCount": 1,
                "members": []
            }
        }
    },
    {
        "name": "BookB",
        "book_id" : "456",
        "book_info": {
            "domain": {
                "domain": null,
                "_events": {},
                "_eventsCount": 1,
                "members": []
            }
        }
    }
]

3 个答案:

答案 0 :(得分:0)

尝试类似的方法(未经测试)

async getAllInfo(person_id)
{

    let book_list = await this.getBooks(person_id);
    for(let book in book_list)
    {
        book_list[book]["book_info"] = this.getBookInfo(book_list[book]["book_id"])
    }

    await Promise
      .all(book_list[book].map(b => b.book_info))
      .then(infos => {
        for (book in infos)
          book_list[book]["book_info"] = infos[book];
        });
    return book_list;
}

答案 1 :(得分:0)

您可以优化这段代码中的操作:

for(let book in book_list) {
    book_list[book]["book_info"] = await this.getBookInfo(book_list[book]["book_id"])
}

因为每本书,您都会提出请求并等待此请求完成,然后再获取下一本书的详细信息。您可以通过以下方式立即执行所有请求,然后等待所有书籍的详细信息被检索:

async getAllInfo(person_id) {

    let book_list = await this.getBooks(person_id);

    // Creating an array of Promises to fetch the details of all the books simultaneously
    const fetchingBooksDetails = book_list.map(book => this.getBookInfo(book.book_id));

    // Wainting for the requests to complete
    const booksDetails = await Promise.all(fetchingBooksDetails);

    // Saving the details of the book in the book_list variable
    booksDetails.forEach((bookDetails, index) => {
      book_list[index].book_info = bookDetails;
    });

    return book_list;
}

答案 2 :(得分:0)

updateUser(editForm) {
  console.log(this.user);
  this.alertify.success('Profile Updated Successfully');
  editForm.reset(this.user);
}