简体   繁体   English

TypeScript异步/等待

[英]TypeScript Async/Await

Good morning! 早上好!

I have the following Angular/TypeScript service, but the query portion of the function happens asynchronously so the return statement is executed before the data is retrieved from the server. 我具有以下Angular / TypeScript服务,但是函数的查询部分是异步发生的,因此在从服务器检索数据之前将执行return语句。 Is there a way to add async/await to this function so it waits for the data to be assigned to the Users variable before executing the return statement? 有没有一种方法可以向此函数添加异步/等待,以便在执行return语句之前等待数据分配给Users变量?

    interface IUserService {
        getAll(): entities.IUser[];
    }

    export class UserService implements IUserService {
        static $inject: string[] = ['dataAccessService'];
        constructor(private dataAccessService: dataAccess.DataAccessService<entities.IUser>) {

        }

        getAll(): app.domain.entities.IUser[] {
            var users: app.domain.entities.IUser[];
            var userResource = this.dataAccessService.getDataResource('https://api.github.com/users');
            userResource.query((data: app.domain.entities.IUser[]) => {
                users = data;
            });

            return users;
        }
    }

    angular
        .module('domain')
        .service('userService',
                    UserService);

With $resource, you can actually set the resource values directly to a variable rather than setting the variable in the callback method. 使用$ resource,您实际上可以直接将资源值设置为变量,而不是在回调方法中设置变量。

interface IUserService {
    getAll(): ng.resource.IResourceArray<ng.resource.IResource<IUser>>;
}

export class UserService implements IUserService {
    static $inject: string[] = ['dataAccessService'];
    constructor(private dataAccessService: dataAccess.DataAccessService<entities.IUser>) {
        var userResource = this.dataAccessService.getDataResource('https://api.github.com/users');
    }

    getAll(): ng.resource.IResourceArray<ng.resource.IResource<IUser>> {
        return userResource.query();
    }
}

angular
    .module('domain')
    .service('userService',
                UserService);

Then in my controller I can set the values directly to my variable to render in my view. 然后,在我的控制器中,我可以直接将值设置为变量以在我的视图中呈现。

class UserController {
    user: ng.resource.IResourceArray<ng.resource.IResource<IUser>>;

    static $inject: string[] = ['UserService'];
    contructor(private userService: IUserService) {

    }

    this.users = this.userService.GetAll();
}

angular.module('app').controller('UserController', UserController);

This will give me access to my user properties as well as some additional properties like the original promise so I can add additional functionality if I would like to. 这将使我能够访问我的用户属性以及一些其他属性,例如原始的Promise,因此我可以根据需要添加其他功能。

Hope that helps anyone with a similar issue. 希望对任何有类似问题的人有所帮助。

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

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