调用未定义的函数时,Javascript不会引发错误

我正在编写一个使用caching系统的nodejs / reactjs应用程序。 我遇到了一个错误,其中caching中的数据从来没有被组件显示,我最终发现,说cache.isEmpty()应该是cache.isempty() 。 在这种情况下,Javascript并没有抛出任何错误,只是停止执行。 另一方面,如果我在其他地方打电话,在if语句之前说,它通常会抛出一个错误,告诉我函数没有被定义。 这是为什么?

 read: function (apiCall, data, cacheKey, ttl, putQuery, retrieveQuery) { if (cache.expired(cacheKey, ttl)) { console.log('cache is expired'); api.call(apiCall,data, (response) => { console.log(response); db[putQuery](response); db[retrieveQuery](data, (result) => { cache.set(cacheKey, result); cache.refresh(cacheKey); render(); }); }); } else if (cache.isEmpty()) { console.log('cache is empty'); db[retrieveQuery](data, (result) => { cache.set(cacheKey, result); render(); }); } console.log('cache is ready'); }, 

让我知道你是否需要更多的细节。

编辑:只是为了说清楚,两个scheme之间的唯一区别是有一次函数在else if语句中调用,而另一次不是。 在这两种情况下,呼叫都以相同的方式发生

在这种情况下,Javascript并没有抛出任何错误,只是停止执行。

是的,它是,它正在抛出一个TypeError因为你试图调用undefined ,这是不可调用的。 但是,无论这个函数是否正在吃掉这个exception,而不是把它提供给你(或者以你的代码没有检查的方式让它提供给你)。

因此,解决scheme是检查是否调用代码的文档,以查看是否以不同的方式报告错误。 这很常见,因为exception跟踪不会跨asynchronous边界传播。

下面是一个吃东西/抑制exception的例子:

 function foo(obj) { obj.undefinedMethod(); } try { foo({}); } catch (e) { console.log("Got an error"); } // But if the caller suppresses it, converting it to // something else... This example converts it to a return value function bar() { try { foo({}); return true; } catch (e) { return false; } } console.log("Before calling bar"); bar(); console.log("After calling bar");