简体   繁体   中英

How to fix 'callback is not a function error'?

I'm trying an easy example using callback function, but it has some problem.

(function ddd () {
  const categories = [];
  const url2 = 'http://www.example.com';

  const callback2 = function (res) {
    console.log(res);
  }

  const callback = function (res,callback2) {
    res.products.forEach((el) => {
      categories.push({itemLabel: el.id, categoryLabel: 'gifts'});
    });
    callback2(categories);
  };

  getData(url2, callback);
})();

And console says callback2 is not a function .

I tried console.log(typeof(callback2)) and it says callback2 is a function.

So, what is the problem in this situation? When I just type console.log(categories) instead, it works well.

你必须做这样的事情。

getData(url2, callback(result, callback2));

You have to do something like this: Important is to pass the second callback already in the first function as a argument.

If you don't what to do this you can store the function in a global variable, but then it's not really a callback.

 (function ddd () { const categories = []; const url2 = 'http://www.example.com'; const callback2 = function (res) { console.log(res); } const callback = function (res,callback2) { res.products.forEach((el) => { categories.push({itemLabel: el.id, categoryLabel: 'gifts'}); }); callback2(categories); }; function getData(url, callback, callback2) { callback({products: [{id: 10}]}, callback2); }; getData(url2, callback, callback2); })(); 

With Global Callback2:

 (function ddd () { const categories = []; const url2 = 'http://www.example.com'; const callback2 = function (res) { console.log(res); } const callback = function (res) { res.products.forEach((el) => { categories.push({itemLabel: el.id, categoryLabel: 'gifts'}); }); callback2(categories); }; function getData(url, callback) { callback({products: [{id: 10}]}); }; getData(url2, callback); })(); 

as i seen you are passing callback2 as a param to function callback, then not load the global definition he uses his own scope definition of callback.

const callback = function (res) {
    res.products.forEach((el) => {
      categories.push({itemLabel: el.id, categoryLabel: 'gifts'});
    });
    callback2(categories);
  };

Removing callback2, from params method, will call callback2 defined previous , and dont find in own scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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