简体   繁体   English

如何将值保存到 function 的变量中?

[英]How to save a value to a variable of a function?

This Code uses the Nativescript Plugin此代码使用 Nativescript 插件

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

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

Console Log: battery charge: 100 %控制台日志:电池电量:100 %

I would like to save this Info.percent to a variable so I can later on reuse it.我想将此 Info.percent 保存到一个变量中,以便以后可以重用它。

Unlucky it always says, that its undefined.不幸的是,它总是说,它未定义。 I tried different approaches.我尝试了不同的方法。

Like:喜欢:

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

or或者

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

var batterystatus = power.startPowerUpdates(function);

or I also tried:或者我也试过:

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

But all pretty much deliver the wrong result.但几乎所有这些都提供了错误的结果。

typeof(Info.percent) = number typeof(Info.percent) = number

The method startPowerUpdates will call the function that you are passing to it, but it seems that startPowerUpdates doesn't return the same returned value. startPowerUpdates 方法将调用您传递给它的 function,但似乎 startPowerUpdates 不会返回相同的返回值。 Either the function is called asynchronously or it simply wasn't programmed for it to return the same value. function 要么被异步调用,要么根本没有被编程为返回相同的值。 Try this instead:试试这个:

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

let batteryPercent;

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

Then check afterward if batteryPercent is set.然后检查是否设置了batteryPercent If it is not then the function is being called in parallel and you'll have to code a trigger to let the program know that the value has been set.如果不是,那么 function 将被并行调用,您必须编写一个触发器来让程序知道该值已设置。 Example:例子:

First check if the function is called synchronously (probably not):首先检查function是否被同步调用(可能不是):

...

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

If the console log is undefined, then you'll need another approach:如果控制台日志未定义,那么您将需要另一种方法:

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
}

Ideally, you should use await and async functions, but that's more advanced.理想情况下,您应该使用 await 和 async 函数,但这更高级。 Don't play with them until problems like the one you had are easy.不要和他们一起玩,直到像你遇到的问题很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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