【问题标题】:How to migrate to callback nodejs如何迁移到回调 nodejs
【发布时间】:2019-03-20 18:16:51
【问题描述】:

我需要将此代码转换为使用回调的干净代码,因为此代码不允许我在其他地方使用正文信息。

const endpoints = [];

function getDevicesFromPartnerCloud() {
  var options = {
    method: 'GET',
    url: 'https://database-dcda.restdb.io/rest/endpoints',
    headers: {
      'cache-control': 'no-cache',
      'x-apikey': '*****************************'
    }
  };
  request(options, function (error, response, body) {
    var data = JSON.parse(body);
    data.forEach(function(data, index) {
      let endpoint = createSceneEndpoint(data._id, data.name);
      endpoints.push(endpoint);
    });
  });
  return endpoints;
}

【问题讨论】:

    标签: node.js callback request asynccallback


    【解决方案1】:

    我认为最干净的方法是使用 Promise 来处理异步 request。要记住的最重要的事情之一是,理想情况下,函数应该只做一件事。这样,它们就更容易测试、推理和重构。我会将实际发出请求的代码拉到一个单独的函数中并让它返回正文,然后让您的getDevicesFromPartnerCloud 调用该新函数,取回数据,并按需要处理它。最重要的是,这“释放”了数据卡在 request 回调中,因为您将其包装在一个 Promise 中,并在数据可用时解决它。

    类似:

    const endpoints = [];
    
    function requestDevices() {
      return new Promise(function(resolve, reject) {
        const options = {
          method: 'GET',
          url: 'https://database-dcda.restdb.io/rest/endpoints',
          headers: {
            'cache-control': 'no-cache',
            'x-apikey': '*****************************',
          },
        };
    
        request(options, function(error, response, body) {
          if (error) {
            reject(error)
          }
    
          resolve({ response: response, body: body });
        });
      });
    }
    
    async function getDevicesFromPartnerCloud() {
      const devicesResponse = await requestDevices();
      const data = JSON.parse(devicesResponse.body);
      data.forEach(function(data, index) {
        const endpoint = createSceneEndpoint(data._id, data.name);
        endpoints.push(endpoint);
      });
    
      // Do whatever else you need with devicesResponse.body
    
      return endpoints;
    }
    

    如果你想更多地向 es6 方向发展,可能是这样的

    let endpoints;
    
    const requestDevices = () =>
      new Promise((resolve, reject) => {
        request(
          {
            method: 'GET',
            url: 'https://database-dcda.restdb.io/rest/endpoints',
            headers: {
              'cache-control': 'no-cache',
              'x-apikey': '*****************************',
            },
          },
          (error, response, body) => (error ? reject(error) : resolve(body)),
        );
      });
    
    const getDevicesFromPartnerCloud = async () => {
      try {
        const body = await requestDevices();
        const data = JSON.parse(body);
        endpoints = data.map(({ _id, name }) =>
          createSceneEndpoint(_id, name),
        );
    
        // Do whatever else you need with devicesResponse.body
        // doStuff(body)
    
        return endpoints;
      } catch (e) {
        console.error(e);
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2017-06-16
      • 1970-01-01
      • 2020-11-09
      • 2018-10-28
      • 2011-11-30
      • 2017-12-12
      • 2017-06-23
      相关资源
      最近更新 更多