我有以下 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 内容。请帮我解决一下这个。
3 回答

叮当猫咪
TA贡献1776条经验 获得超12个赞
你有没有考虑过以不同的方式看待这个问题?如果其他 API 也是这种情况,我会考虑将这些 API 聚合到聚合器服务或 API 本身(如果可以)。
一次接收您需要的所有数据总是更好,而不是多次调用,这会导致延迟和复杂性。
添加回答
举报
0/150
提交
取消