簡體   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