【发布时间】:2021-06-10 01:26:57
【问题描述】:
我需要构建一个显示 2 个数组的对象。为此,我调用第一个 Promise,然后使用它的结果调用第二个 Promise。
我想知道是否有解决此问题的最佳方法。
问题描述如下。
/**
* DO NOT USE ASYNC/AWAIT
* Using the below two functions produce the following output
* {
* authors: ['bob', 'sally'],
* titles: ['Greeting the World', 'Hello World!']
* }
* */
const getBooks = () => {
return new Promise((resolve) => {
resolve([
{
bookId: 1,
author: "bob"
},
{
bookId: 2,
author: "sally"
}
]);
});
};
const getTitle = (bookId) => {
return new Promise((resolve, reject) => {
switch (bookId) {
case 1:
resolve({ title: "Greeting the World" });
break;
case 2:
resolve({ title: "Hello World!" });
break;
default:
reject(new Error("404 - book not found"));
}
});
};
let authors = {authors: [], titles: []}
getBooks()
.then(result => {
result.map(
t => {
authors.authors.push(t.author)
getTitle(t.bookId)
.then(result => {
authors.titles.push(result.title)
})
})
}).then(_ => console.log(authors))
【问题讨论】:
-
当错误提示文本不足时,请不要再复制粘贴相同的文本。尝试以不同的方式实际解释问题。你在这里没有做任何异步的事情,所以不清楚你为什么要使用 Promises。这是应该解释的事情,而不是重复相同的文字。
标签: javascript asynchronous ecmascript-6 es6-promise event-loop