首页 > 解决方案 > Nodejs - 回调函数仅在存在错误时执行?

问题描述

我正在尝试使用此节点库(https://www.npmjs.com/package/node-wifi)编写一个函数以连接到 wifi 网络,但似乎每当我执行此函数时,除非实际上是错误目前,回调被完全跳过。我可能误解了回调的工作方式,但即使没有检测到错误,它也不应该执行吗?

function ConnectToNetwork(networkName: string, networkPassword: string) {
  // Connect to a network
  wifi.disconnect();
  wifi.connect({ ssid: networkName, password: networkPassword }, function (err) {
    //This is not logged when no error is present
    console.log("callback?");
    if (err) {
      console.log(err);
      console.log("Couldn't connect to network");
      return createFailureWindow();
    }
      //Shouldn't this part of the function be invoked if there is no error?
      UpdateCurrentConnections();
      createSuccessWindow();
      console.log("Connected");

  });
}

标签: javascriptnode.jsfunctioncallbackinvoke

解决方案


您可以尝试断开回调吗?

function ConnectToNetwork(networkName: string, networkPassword: string) {
  // Connect to a network
  wifi.disconnect(function(err) {
  if (err) {
    console.log(err);
  }
  console.log("Disconnected");
  wifi.connect({ ssid: networkName, password: networkPassword }, function (err) {
    //This is not logged when no error is present
    console.log("callback?");
    if (err) {
      console.log(err);
      console.log("Couldn't connect to network");
      return createFailureWindow();
    }
      //Shouldn't this part of the function be invoked if there is no error?
      UpdateCurrentConnections();
      createSuccessWindow();
      console.log("Connected");

  });
});
  
}


推荐阅读