繁体   English   中英

如何在javascript的catch函数中将参数传递给回调函数

[英]how to pass the arguments to the call back function in catch function in javascript

我正在编写代码,只是觉得需要......我想将额外的参数(即 msg)传递给回调函数renderError()函数以及由 catch 函数本身在 catch 函数中生成的默认错误参数

我也不能这样做.catch(renderError(err,'this is msg'));
因为它将成为function call ,据我所知,我们只需要将回调函数传递higher order function ,而不是在那里调用它

  • 那么我怎样才能通过它,以便我的 msg 参数

注意 - 请不要参考其他代码,因为我已经从我的代码中提取了一个简短的片段——我只想将参数传递给我的回调函数,即renderError()

const renderError = function (err, msg) {
  console.log(err);

  countriesContainer.insertAdjacentText('beforeend', msg);
  countriesContainer.style.opacity = 1;
};

const getCountryData = function (country) {
  fetch(`https://restcountries.com/v2/name/${country}`)
    .then(
      response => response.json()
      // err => console.log(err)
    )
    .then(data => {
      renderCountry(data[0]);
      const neighbour = data[0].borders[0];

      if (!neighbour) return;

      return fetch(`https://restcountries.com/v2/alpha/${neighbour}`);
    })
    .then(
      response => response.json()
      // err => console.log(err)
    )
    .then(data => renderCountry(data, 'neighbour'))
    .catch(renderError);           //  ---->> here I want to pass the message that will be 
                                   //  display along with the call back function 
};
btn.addEventListener('click', function () {
  getCountryData('germany');
});

将您的renderError调用包装在一个公开error值的函数中。

.catch(error => {
  renderError(error, 'Your custom error message');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM