Angular2将服务方法从回调更改为Async

时间:2017-07-14 22:27:02

标签: javascript angular asynchronous angular-promise

我启动了一个简单的Angular2 Electron应用程序,我有一个查询本地SQL Server数据库的服务方法。到目前为止一切正常。现在我试图将服务DB调用的结果发送到我的组件并以某种方式显示它。

问题在于查询逻辑是针对回调语法编写的:

player --> [P], { regular_player(P) }.
expert --> [E], { expert_player(E) }.

我很难重写它以返回一个promise,因为结果将始终在查询命令函数的result参数内。我的组件如下所示:

sql.query(sqlString, (err, result) => {
    ...
    callback(result);
    ...
});

我的服务看起来像这样:

export class LinkDocRetriever {

  constructor(private myService: MyService) {  }

  results = "";

  loadMyData(id: number): void {

    let tcData = this.myService.getMyData();
    tcData.forEach(element => {
      this.results += element.FileName + " " +  "....\n";
    });

  };
}

我确实得到了一个结果,但是组件永远不会看到它,因为它会在返回结果之前返回。

我已尝试在ConnectionPool函数中对查询调用进行等待,但是我收到一条错误,指出只能在异步函数中调用await,即使我在该方法上设置了异步。 mssql包有Async/ Await section,但是当我尝试时,该页面上给定的语法会出错。

知道我怎么能用诺言写这个吗?

1 个答案:

答案 0 :(得分:4)

正如您所指出的,有三种方法可以处理异步函数:使用回调,使用promise和使用Async / Await。我将尝试展示所有三种方式,但您应该了解javascript中的事件循环以及它如何处理异步函数。

<强>回调

回调是技术上处理异步函数的最快方法,但它起初非常混乱,如果使用不当可能会创建一个叫做回调地狱的东西。回调地狱非常糟糕,甚至有人为它创建了一个网站http://callbackhell.com/

因此您可以将代码重写为:

export class LinkDocRetriever {

  constructor(private myService: MyService) {  }

  results = "";

  loadMyData(id: number): void {

    // call getMyData with a function as argument. Typically, the function takes error as the first argument 
    this.myService.getMyData(function (error, tcData) {
       if (error) {
         // Do something
       }

       tcData.forEach(element => {
         this.results += element.FileName + " " +  "....\n";
       });
    });
  };
}

服务

import { Injectable } from "@angular/core";
import * as sql from "mssql";

@Injectable()
export class MyService {
    // Now getMyData takes a callback as an argument and returns nothing
    getMyData(cb) {

        let myData = [];

        let config = {
            user: "sa",
            password: "xxx",
            server: "localhost",
            database: "mydb"
        };

        const pool1 = new sql.ConnectionPool(function(config, err) {

            if (err) {
                // Error occured, evoke callback
                return cb(error);
            }

            let q:string = `SELECT TOP 10 * FROM MyTable;`;

            let final = pool1.request()
            .query<MyItem>(q, (err, result) => {
                if (err) {
                    console.log("request err: " + err);
                    // Error occured, evoke callback
                    return cb(error);
                }

                console.log("db result count: " + result.recordsets[0].length);
                result.recordsets[0].forEach(row => {
                    myData.push(row);
                });

                // Call the callback, no error occured no undefined comes first, then myData
                cb(undefined, myData);
            });

        });
    }
}

<强>无极

Promise是一个特殊对象,允许您控制异步函数并避免回调地狱,因为您不必使用嵌套回调,而只使用一个级别thencatch函数。阅读更多关于Promise here

的信息

组件

export class LinkDocRetriever {

  constructor(private myService: MyService) {  }

  results = "";

  loadMyData(id: number): void {
    this.myService.getMyData()
      .then((tcData) => {
         // Promise uses then function to control flow
         tcData.forEach((element) => {
           this.results += element.FileName + " " +  "....\n";
         });
      })
      .catch((error) => {
         // Handle error here
      });

  };
}

服务

@Injectable()
export class MyService {
    // Now getMyData doesn't take any argument at all and return a Promise
    getMyData() {

        let myData = [];

        let config = {
            user: "sa",
            password: "xxx",
            server: "localhost",
            database: "mydb"
        };

        // This is what getMyData returns
        return new Promise(function (resolve, reject) {
            const pool1 = new sql.ConnectionPool((config, err) => {

                if (err) {
                    // If error occurs, reject Promise
                    reject(err)
                }

                let q = `SELECT TOP 10 * FROM MyTable;`;

                let final = pool1.request()
                  .query(q, (err, result) => {
                      if (err) {
                          // If error occurs, reject Promise
                          reject(err)
                      }

                      console.log("db result count: " + result.recordsets[0].length);
                      result.recordsets[0].forEach((row) => {
                          myData.push(row);
                      });

                      // 
                      resolve(myData);
                  });

            });
        })

    }
}

<强>异步/ AWAIT

引入了Async / await来解决处理回调和承诺时遇到的困惑。阅读更多关于async / await here

的信息

组件

export class LinkDocRetriever {

  constructor(private myService: MyService) {  }

  results = "";

  // Look. loadMyData now has to have async keyword before to use await. Beware, now loadMyData will return a Promise.
  async loadMyData(id) {

    // By using await, syntax will look very familiar now
    let tcData = await this.myService.getMyData(tcData);
    tcData.forEach((element) => {
      this.results += element.FileName + " " +  "....\n";
    });
  };
}

服务与承诺完全相同,因为 Async / await 是专门为处理它们而创建的。

注意:我从代码中删除了一些Typescript功能,因为我更习惯于使用vanilla JS,但是你应该能够编译它们,因为Typescript是JS的超集。