[Javascript] Run asynchronous functions in sequence using reduce
JavaScript in Using run sequence reduce Functions Asynchronous
2023-09-14 09:00:48 时间
This can be handy if you have a rate limit on API requests or if you need to pass the result of each promise to the next one.
function fetchMessages(username) { return fetch(`https://example.com/api/messages/${username}`) .then(response => response.json()); } function getUsername(person) { return person.username; } async function chainedFetchMessages(p, username) { // In this function, p is a promise. We wait for it to finish, // then run fetchMessages(). const obj = await p; const data = await fetchMessages(username); return { ...obj, [username]: data}; } const msgObj = peopleArr .map(getUsername) .reduce(chainedFetchMessages, Promise.resolve({})) .then(console.log); // ⦘ {glestrade: [ … ], mholmes: [ … ], iadler: [ … ]}
相关文章
- javascript/JS常用正则表达式
- HTML5中新增Javascript特性
- JavaScript-MD5加密
- JavaScript从父页面获取子页面的值(子页面又如何访问父页面)
- javascript、js操作json对象和字符串互相转换方法
- [Javascript] Object.freeze: using Object.freeze in function params to enforce immutabtility
- [Javascript] Swap array item in place using splice()
- [Javascript] Private class properties in Javascript
- [ES2019] Represent Collision-free String Constants as Symbols in JavaScript
- [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
- [Javascript] Await a JavaScript Promise in an async Function with the await Operator
- [Algorithom] Stack Data Structure in JavaScript
- [Javascript] Identify and Deal with NaN in JavaScript
- [Javascript ] Array methods in depth - sort
- javascript: 复制对象时的深拷贝及浅拷贝(chrome 105.0.5195.125)
- 新手学JavaScript(三)----超酷消息警告框插件(SweetAlert)
- [XState] Create Actor in Vanilla Javascript
- [Javascript] Understanding the difference between .prototype and .__proto__ in JavaScript
- [Algorithm] Write your own Math.pow function in Javascript, using Recursive approach
- [Algorithms] Solve Complex Problems in JavaScript with Dynamic Programming
- [Algorithms] Refactor a Loop in JavaScript to Use Recursion
- [Javascript] Use a custom sort function on an Array in Javascript
- [Javascript Crocks] Apply a function in a Maybe context to Maybe inputs (curry & ap & liftA2)
- [Javascript] String Padding in Javascript using padStart and padEnd functions
- [Javascript] this in Function Calls
- [Javascript] Classify JSON text data with machine learning in Natural
- Compare assert exception in should(JavaScript) and unittest(Python)
- javascript:页面中有多处window.onload时的处理(chrome 105.0.5195.125)
- atitit.javascript调用java in swt attilax 总结
- 一串最简单的JavaScript代码,在Chrome开发者工具调试器里触发VM8标签的出现
- initializeCachedDB function in JavaScript - how is the call delegated to
- 从零开始学_JavaScript_系列(17)——CSS<4>(定位、遮罩、float、弹性布局flex)
- Array_JavaScript