如何迁移到回调nodejs



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

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;
}

我认为最干净的方法是使用承诺处理异步request。要记住的最重要的事情之一是,理想情况下应该只做一件事。这样,它们更容易测试,推理和重构。我将实际将请求的代码拉到单独的函数中,并让其返回正文,然后将您的getDevicesFromPartnerCloud调用the新功能,重新获取数据并根据需要进行处理。最重要的是,这"释放"了卡在request回调中的数据,因为您将其包裹在承诺中,并在数据可用时解决。

类似:

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);
  }
};

最新更新