Reputation: 130
I just read a article about promise
. And I am really confused.
Why is
const bookPromise = bookModel.fetchAll();
const authorPromise = authorModel.fetch(authorId);
const book = await bookPromise;
const author = await authorPromise;
is a better way than
const books = await bookModel.fetchAll();
const author = await authorModel.fetch(authorId);
The author explained that it make the promise serial execution
. But i justcan not see the difference. Can you explain about this to me. Thx.
Upvotes: 2
Views: 46
Reputation: 370729
In the first snippet, both Promise
s are declared, and the asynchronous code for both starts running immediately - both network requests (or whatever the operation is) gets sent out immediately. In the second snippet, the author
Promise does not start until the books
Promise has resolved - if latency is high, for example, that could be a problem. Better to send out both requests at once, rather than requiring one to be completed before starting the other one.
It might be clearer to use Promise.all
instead, though:
const [book, author] = await Promise.all([
bookModel.fetchAll(),
authorModel.fetch(authorId)
]);
Upvotes: 3