简体   繁体   English

Promise在knn分类器tensorflow完成后执行代码

[英]Promise to execute code after knn classifier tensorflow is finished

Im using knn classifier in tensorflow.js from this example .我在此示例中的 tensorflow.js 中使用 knn 分类器。 Sometimes it is a little bit slow of adding the new examples when doing transfer learning so I want to create a promise that waits for the new example to be added before a the code continues to execute.有时在进行迁移学习时添加新示例有点慢,所以我想创建一个 promise 等待添加新示例,然后代码继续执行。 I havnt used promises a lot so Im a bit lost.我没有经常使用承诺,所以我有点迷茫。 I tried this我试过这个

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

but it doesnt work however.但它不起作用。 I also tried this according to the documentation on w3schools but didnt work either我也根据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 */
    }
  );

What am I doing wrong?我究竟做错了什么? How can I accomplish this?我怎样才能做到这一点?

In an async function, await can be used在异步 function 中,可以使用await

async animate() {

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

}

You could try something like this:你可以尝试这样的事情:

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');
    }
});

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

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