将AWIS调用转换为异步函数:现有AlexaCall函数改造需求
Refactoring the AlexaCall Function to Use Async/Await
Hey there! Let's turn that callback-heavy AWIS call into a clean, maintainable async function. Async/await makes asynchronous code read much more like synchronous code, which is way easier to follow and debug. Here's the refactored version:
async function AlexaCall(websites) { const awis = require('awis'); const client = awis({ key: keys.alexa.public, secret: keys.alexa.secret }); // Wrap the callback-based client request in a Promise const fetchAlexaRankData = (urls) => { return new Promise((resolve, reject) => { // Dynamically build the request parameters from the URLs array const requestParams = { Action: 'UrlInfo', 'UrlInfo.Shared.ResponseGroup': 'Rank' }; urls.forEach((url, index) => { requestParams[`UrlInfo.${index + 1}.Url`] = url; }); client(requestParams, (err, data) => { if (err) { reject(err); // Pass errors to the Promise's reject handler return; } resolve(data); // Resolve with the successful response data }); }); }; try { // Use await to wait for the Promise to resolve const responseData = await fetchAlexaRankData(websites); // Your existing processing logic goes here console.log(`Successfully fetched data for ${responseData.length} websites`); // do... (your original processing code) return responseData; // Return the processed data to the caller } catch (error) { // Handle any errors that occur during the request or processing console.error('Failed to fetch Alexa data:', error); throw error; // Re-throw the error if you want the caller to handle it too } } // Example usage: // AlexaCall(['lupomontero.com', 'yahoo.com', 'weibo.com', 'github.com', 'monono.org']) // .then(processedData => console.log('Final results:', processedData)) // .catch(err => console.error('Request failed:', err));
Key Improvements & Explanations:
- Promise Wrapping: Since the
awisclient uses callbacks, we wrap its call in a Promise. This lets us leverageasync/awaitinstead of dealing with messy nested callback logic. - Dynamic Parameter Building: Instead of hardcoding each
UrlInfo.N.Urlentry, we generate them from an input array of websites. This makes the function flexible—you can pass any number of URLs without modifying the request structure. - Clean Error Handling: Using
try/catchwithawaitcentralizes error handling, making it easier to manage failures compared to checkingerrin a callback. - Async Function Signature: Marking
AlexaCallasasyncmeans it returns a Promise, so callers can use either.then()/.catch()orawaitit in their own async code.
内容的提问来源于stack exchange,提问作者Alex Ironside
相关产品推荐
相关产品推荐

