【发布时间】:2020-08-25 17:31:06
【问题描述】:
我正在调用 Udemy API。为了同时拨打电话,我使用了一个循环。通过这样做,我会自动增加页码并尝试从每个页面中获取数据并将其存储到一个数组中,以便我可以将所有数据以 json 格式写入单个文件中。但我得到的只是一个空数组。如何访问 promise 返回的值并存储到 doc.table 数组中?
我的代码:
const fetch=require("node-fetch");
const fs=require("fs");
let doc={};
doc.table=[];
for(let i=1;i<=10;i++){
fetch('https://www.udemy.com/api-2.0/courses/ page='+i+'&page_size=10&client_id=${client_id}&client_secret=${client_secret},{
method:'GET',
body:null,
headers:{authorization: ${auth_code}}
})
.then(res=>res.json())
.then(json=>doc.table.push(json))
};
fs.writeFile("UDEMY.json",JSON.stringify(doc),function(err){
if(err) throw err;
console.log("Complete");
});
【问题讨论】:
-
由于 promises 是异步的,所以在使用任何结果之前,您需要等待它们解决 - 最简单的方法是使用 async/await,然后等待
fetch- 当然,代码将需要在async function... 或只是在(async () => { ... all the code from for loop to all the writefile code ...})();内 -
您发布的代码中有两件事要注意......您似乎想使用模板字符串,但没有正确使用,并且不需要
;关闭}一个for循环
标签: javascript node.js json es6-promise fetch-api