如何使用线程或任务调用javascript函数?

时间:2019-05-23 10:50:35

标签: javascript c# asp.net webforms

我在下面尝试了以下代码

.cs

    string someone = "John";
    int timer = 3000;
    int check = 1;
    string script = "<script> runPromise('" + someone + "'," + timer + "," + check + ").then(someone => { console.log('" + someone + "', someone)});</script>";
    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", script);

.aspx

<script>
    let runPromise = (someone, timer, check, success = true) => {
        console.log(`${someone} start run`);
        console.log(check);
      return new Promise((resolve, reject) => {
        if (check == 1) {
          setTimeout(function () {
            resolve(`${someone} run ${timer / 1000} second`);
          }, timer);
        } else {
          reject(`${someone} fail`)
        }
      });
    }
</script>

此代码只能在按钮中使用。

当我要等待10秒钟时如何在线程或任务中使用它?

我们将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用setTimeout

来兑现承诺

已编辑

string someone = "John";
int timer = 10000;
int check = 1;
string script = "<script> setTimeout(() => someFunction(('" + someone + "'," + timer + "," + check + ").then(value => {console.log(value);}), " + timer + ");</script>";
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", script);

var someFunction = (someone, timer, check) => {
  console.log(`${someone} start run`);
  console.log(check);

  return new Promise((resolve, reject) => {
    if (check == 1) {
      resolve(`${someone} run ${timer / 1000} second`);
    } else {
      reject(Error("It broke"));
    }
  });
};

样本:

var someFunction = (someone, timer, check) => {
  console.log(`${someone} start run`);
  console.log(check);
  
  return new Promise((resolve, reject) => {
    if (check == 1) {
      resolve(`${someone} run ${timer / 1000} second`);
    } else {
      reject(Error("It broke"));
    }
  });
};

setTimeout(() => someFunction(`someone`, 10000,1).then(value => {
console.log(value);
}), 10000);