JavaScript中fetch请求数据push入数组后未同步到导出对象desc字段问题
问题根源
你遇到的是JS异步执行顺序的问题:
fetch是异步API,调用后会立刻返回Promise,不会等待接口响应,代码会继续向下执行- 你导出
team数组的代码是同步执行的,执行时fetch还没拿到接口返回的贡献者数据,contributors此时只有初始的["Here is a list of them:"]内容,所以join生成的desc自然只有初始值 - 等你在控制台看到数组有数据时,是
fetch已经完成响应、异步回调执行完往数组里push了新元素,但此时team里的desc是早就生成好的静态字符串,不会跟着数组更新自动变化 - 另外你原代码里
.then(console.log(contributors))的写法是错误的,你直接同步调用了console.log并把返回值传给了then,并不是等异步完成后再打印,你看到的控制台数组内容是浏览器控制台对引用类型的延迟求值导致的,不是打印时就已经有数据。
修复方案
可以用ES模块支持的Top-level await来等待异步请求完成后再导出数据,修正后代码如下:
// 先等待fetch请求完成,拿到贡献者数据 const contributors = await fetch('https://api.github.com/repos/kayano-bot/kayano/contributors') .then(response => response.json()) .then(data => { // 把初始提示和返回的用户名拼在一起 return ["Here is a list of them:", ...data.map(user => user.login)] }) // 等contributors数据准备完成后再定义导出的team数组 export const team = [ { 'name': 'Pukima', 'discrim': '7331', 'mainRole': 'Main Dev & Creator', 'secRoles': 'Ideas, Planning, Mannager, Code, Maintain, Dependencies, Reviewer', 'desc': 'Pukima is the Main Dev and Creator of Kayano. He had the idea behind Kayano and wanted to create Kayano because he didn\'t wanted to pay for a bot which does not even have everything he needed. So he decided to create his own bot. Later he invited bolo to join his journey and to help out.' }, { 'name': 'bolo', 'mainRole': 'Secondary Dev', 'desc': 'bolo is the newest addition to the Kayano team and she\'s helping out Pukima with developing the bot and eventually even the website. Not much more to say for now except: "Welcome to the team!"' }, { 'name': 'All other awesome contributors!', 'desc': contributors.join('\n'), }, { 'name': 'You?', 'mainRole': 'Marketing, Web Backend, discord.js Dev', 'shortDesc': 'We are searching for new Members to join the team! Contact Pukima for more informations.', } ]
如果你的运行环境不支持Top-level await,也可以把导出改成返回Promise的函数:
export async function getTeam() { const contributors = await fetch('https://api.github.com/repos/kayano-bot/kayano/contributors') .then(response => response.json()) .then(data => ["Here is a list of them:", ...data.map(user => user.login)]) return [ // 和上文一致的team数组完整内容 ] } // 导入方使用时需要await getTeam()拿到数据
内容的提问来源于stack exchange,提问作者Pukima
相关产品推荐
相关产品推荐

