You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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 awis client uses callbacks, we wrap its call in a Promise. This lets us leverage async/await instead of dealing with messy nested callback logic.
  • Dynamic Parameter Building: Instead of hardcoding each UrlInfo.N.Url entry, 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/catch with await centralizes error handling, making it easier to manage failures compared to checking err in a callback.
  • Async Function Signature: Marking AlexaCall as async means it returns a Promise, so callers can use either .then()/.catch() or await it in their own async code.

内容的提问来源于stack exchange,提问作者Alex Ironside

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:51:17