【问题标题】:Promise to execute code after knn classifier tensorflow is finished承诺在 knn 分类器 tensorflow 完成后执行代码
【发布时间】:2021-02-03 16:03:39
【问题描述】:

我在这个example 中使用 tensorflow.js 中的 knn 分类器。有时在进行迁移学习时添加新示例有点慢,所以我想创建一个承诺,等待添加新示例,然后代码继续执行。我没有经常使用承诺,所以我有点迷茫。我试过这个

  new Promise(this.knn.addExample(logits, this.training)).then(
    console.log("print this message to the console after the training is done);
  );

但它不起作用。 我也根据documentation on w3schools 尝试过,但也没有用

  let myPromise = new Promise(function(myResolve, myReject) {
    // Add the example to the training
    this.knn.addExample(logits, this.training)

    myResolve(); // when successful
    myReject(); // when error
  });

  myPromise.then(
    function(value) {
      console.log("print this message to the console after the training is done")
      /* code if successful */
    },
    function(error) {
      /* code if some error */
    }
  );

我做错了什么? 我怎样才能做到这一点?

【问题讨论】:

  • this.knn.addExample 是异步函数吗?
  • 嗯。它在async animate() { } 函数中运行。我不确定这是否会成为异步函数?

标签: javascript tensorflow promise tensorflow.js


【解决方案1】:

在异步函数中,可以使用await

async animate() {

  await this.knn.addExample(logits, this.training) // wait until the promise is resolved

}

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    const mypromise = new Promise((resolve) => {
        /* if this.knn.addExample returns true/false 
           you may use it below instead of resolve(true)
        */
        this.knn.addExample(logits, this.training); 
        resolve(true);
    });
    mypromise.then((res) => {
        if(res) {
            // code you want to execute
        } else {
           throw new Error('This error explains why this.knn.addExample returned false');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2017-05-26
      • 2019-01-21
      • 2018-05-09
      • 1970-01-01
      • 2012-02-08
      • 2020-11-25
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多