我有以下 2 个 URL 的一些模拟数据:
1. Get the list of users from 'https://myapp.com/authors'.
2. Get the list of Books from 'https://myapp.com/books'.
现在我的任务是按名称对书籍进行排序,并将排序后的列表mysortedbooks.json作为 JSON写入文件
然后我必须创建一个具有书籍属性的作者数组,其中包含该作者的所有书籍。
如果作者没有书,那么这个数组应该是空的。在这种情况下不需要排序,数据应authorBooks.json作为 JSON存储在文件中。
现在我必须返回一个在上述步骤完成后解决的承诺。例如,我应该saveToFile在下面的代码中返回最终调用。
const fs = require('fs');
function getFromURL(url) {
switch (url) {
case 'https://myapp.com/authors':
return Promise.resolve([
{ name: "Chinua Achebe", id: "1" },
{ name: "Hans Christian Andersen", id: "2" },
{ name: "Dante Alighieri", id: "3" },
]);
case 'https://myapp.com/books':
return Promise.resolve([
{ name: "Things Fall Apart", authorId: "1" },
{ name: "The Epic Of Gilgamesh", authorId: "1" },
{ name: "Fairy tales", authorId: "2" },
{ name: "The Divine Comedy", authorId: "2" },
{ name: "One Thousand and One Nights", authorId: "1" },
{ name: "Pride and Prejudice", authorId: "2" },
]);
}
}
const outFile = fs.createWriteStream('...out-put-path...');
function saveToFile(fileName, data) {
outFile.write(`${fileName}: ${data}\n`);
return Promise.resolve();
}
function processData() {
const authors = getFromURL('https://myapp.com/authors').then(author => {
return authors;
});
const books = getFromURL('https://myapp.com/authors').then(books => {
return books.sort();
});
我必须实现的主要逻辑是processData方法。
我尝试添加代码来解决需求,但promise在所有操作后如何返回都被卡住了。还有如何构建我的authorAndBooksJSON 内容。
请帮我解决一下这个。
叮当猫咪
相关分类