在数组映射函数中使用类的`this`对象与async,await - Nodejs,Javascript

时间:2017-09-19 05:11:55

标签: javascript arrays node.js

我需要用来在map函数中调用这个对象。我已经按照相关答案了。但所有人都表现出同样的例外。

这是我的班级

const userServiceClient = require("./clients/user-service-client.js");

class GetProfilesByQueryHandler {

    constructor(userRepo) {
        this.userRepo = userRepo;
    }

    /**
     * Returns profiles
     * @param {any} req 
     */
    async handleHttp(req) {
        const users = await userServiceClient.getUserByQuery(query, req.reqId);      

        users.map((user) => {
            user.profile = await this.userRepo.findByReferenceId(user.id);
        });

        console.log(users);
    }

}

module.exports = GetProfilesByQueryHandler;

我尝试过以下方法并抛出相关的异常。

users.map((user) => {
    user.profile = await this.userRepo.findByReferenceId(user.id);
});

----------------- Result ------------------------------

user.profile = await this.userRepo.findByReferenceId(user.id);',
     '                                 ^^^^',
     'SyntaxError: Unexpected token this',
######################################################

users.map(function(user) {
        user.profile = await this.userRepo.findByReferenceId(user.id);
}.bind(this));

----------------- Result ------------------------------

user.profile = await this.userRepo.findByReferenceId(user.id);',
    '                                 ^^^^',
'SyntaxError: Unexpected token this'

######################################################

users.map(this._getProfile, {repo: this.userRepo});

_getProfile(user) {
        return user.profile = await this.repo.findByReferenceId(user.id);
}

----------------- Result ------------------------------

'        return user.profile = await this.repo.findByReferenceId(user.id);',
'                                    ^^^^',
'',
'SyntaxError: Unexpected token this',

######################################################
var self = this;

users.map((user) => {
    user.profile = await self.userRepo.findByReferenceId(user.id);
});

----------------- Result ------------------------------

'            user.profile = await self.userRepo.findByReferenceId(user.id);',
'                                 ^^^^',
'',
'SyntaxError: Unexpected identifier',

######################################################
var that = this;

users.map((user) => {
    user.profile = await that.userRepo.findByReferenceId(user.id);
});

----------------- Result ------------------------------

'            user.profile = await that.userRepo.findByReferenceId(user.id);',
'                                 ^^^^',
'',
'SyntaxError: Unexpected identifier

######################################################
var obj = {repo: this.userRepo};

users.map((user) => {
    user.profile = await this.repo.findByReferenceId(user.id);
}, obj);

----------------- Result ------------------------------

'            user.profile = await this.repo.findByReferenceId(user.id);',
'                                 ^^^^',
'',
'SyntaxError: Unexpected token this',

######################################################

这样做的方法是什么。很多问题都与此有关。但所有答案都不适合我。

2 个答案:

答案 0 :(得分:2)

编辑:如果您想记录并返回异步调用的实际结果,我添加了第二个代码段。希望能帮助到你!

您只需错过箭头功能中的async关键字:

const userServiceClient = require("./clients/user-service-client.js");

class GetProfilesByQueryHandler {

    constructor(userRepo) {
        this.userRepo = userRepo;
    }

    /**
     * Returns profiles
     * @param {any} req 
     */
    async handleHttp(req) {
        const users = await userServiceClient.getUserByQuery(query, req.reqId);      
        //I added a "async" here. 
        users.map(async (user) => {
            user.profile = await this.userRepo.findByReferenceId(user.id);
        });
        //Without this async, your arrow function is not aynchronous 
        //and  you can't use await within it.
        
        //BTW this console.log won't log users after the map upper. 
        console.log(users);
    }

}

module.exports = GetProfilesByQueryHandler;

我无法测试,但它在语法上是正确的。

返回结果的第二种可能性:

const userServiceClient = require("./clients/user-service-client.js");

class GetProfilesByQueryHandler {

    constructor(userRepo) {
        this.userRepo = userRepo;
    }

    /**
     * Returns profiles
     * @param {any} req 
     */
    async handleHttp(req) {
        const users = await userServiceClient.getUserByQuery(query, req.reqId);
        //I added a "async" here. The promises are now put in a table
        const tableOfPromises = users.map(async(user) => {
            user.profile = await this.userRepo.findByReferenceId(user.id);
        })
        //The engine will stop executing the code here untill all your promises return.
        const finalResult = await Promise.all(tableOfPromises)
        //All your promises have returned.
        console.log(users)
        return finalResult
    }

}

module.exports = GetProfilesByQueryHandler;

答案 1 :(得分:0)

未经测试但应该有效。 尝试明确设置上下文

users.map(this._getProfile.call({repo: this.userRepo}));

_getProfile(user) {
        var self = this;
        return function (user) { user.profile = await self.repo.findByReferenceId(user.id); }
}