【问题标题】:How to save a value to a variable of a function?如何将值保存到函数的变量中?
【发布时间】:2019-10-28 15:35:11
【问题描述】:

此代码使用 Nativescript 插件

let power = require("nativescript-powerinfo");

power.startPowerUpdates(function (Info) {
    console.log("battery charge: " + Info.percent + "%");
});

控制台日志:电池电量:100 %

我想将此 Info.percent 保存到一个变量中,以便以后可以重用它。

不幸的是,它总是说它未定义。我尝试了不同的方法。

喜欢:

var batterystatus = power.startPowerUpdates(function(Info){
      return Info.percent;
}

power.startPowerUpdates(function(Info){
          return Info.percent;

var batterystatus = power.startPowerUpdates(function);

或者我也试过了:

var batterystatus = power.startPowerUpdates(function(Info){
          this.batterystatus = Info.percent
}

但几乎所有的结果都是错误的。

typeof(Info.percent) = number

【问题讨论】:

  • startPowerUpdates(...) 是在自己的上下文中执行的回调。最后一个选项可行,但您必须保留上下文,您可以使用箭头函数来执行此操作。还要确保在 NgZone 中运行它。如果您是 JavaScript / TypeScript 新手,我建议您先了解基础知识。
  • 旁注:有一个错字,this.battterystatus = Info.percent 带有三个“t”。不一定与主要问题有关。
  • 我不明白为什么投反对票,这是一个完全可以接受的问题。

标签: javascript angular typescript nativescript


【解决方案1】:

方法 startPowerUpdates 将调用您传递给它的函数,但似乎 startPowerUpdates 不会返回相同的返回值。该函数要么被异步调用,要么根本没有被编程为返回相同的值。试试这个:

let power = require("nativescript-powerinfo");

let batteryPercent;

power.startPowerUpdates(function (Info) {
    batteryPercent = Info.percent;
    console.log("battery charge: " + batteryPercent + "%");
});

然后检查是否设置了batteryPercent。如果不是,则该函数被并行调用,您必须编写一个触发器来让程序知道该值已被设置。示例:

先检查函数是否被同步调用(可能不是):

...

console.log(batteryPercent); // check the value here

如果控制台日志未定义,那么您将需要另一种方法:

let updateBatteryPercent = (newBatteryPercent) => {
    batteryPercent = newBatteryPercent;
    continueExecutionFunction();
}

// and now you should have:
power.startPowerUpdates(function (Info) {
    console.log("battery charge: " + Info.percent+ "%");
    updateBatteryPercent(Info.percent);
});

function continueExecutionFunction() {
    // here you should have whatever you'd like to
    // happen after you find out the battery percent
}

理想情况下,您应该使用 await 和 async 函数,但这更高级。在你遇到的问题很容易之前,不要和他们一起玩。

【讨论】:

  • 哇太棒了!有时第一次调用是未定义的,但之后它似乎工作得很好!非常感谢!
  • 我做到了,但由于我的低声誉 (12) 低于 15,分数尚未公开。但我想它很快就会:)
  • @sensenmann 你只是神奇地赢得了声誉(大声笑不是我;))。再试一次。顺便说一句,我注意到您最近一直在回答几个问题。我建议您给出一些高质量的答案,而不是许多低质量的答案。
猜你喜欢
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2010-10-09
相关资源
最近更新 更多