简体   繁体   English

在数组映射函数中将类的`this`对象与async,await一起使用-Node.js,Javascript

[英]Use `this` object of the class in array map function with async, await - Nodejs, Javascript

I need to use to call this object in the map function. 我需要用于在map函数中调用此对象。 I already followed related answers. 我已经关注了相关答案。 But all are showing same exception. 但是所有人都显示出相同的例外。

This is my class 这是我的课

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;

I have tried following ways and it throwing related exceptions. 我尝试了以下方法,并且抛出了相关的异常。

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',

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

What is the way to do this. 有什么办法做到这一点。 Lot of questions are related with this. 许多问题与此有关。 But all answers is not working for me. 但是所有的答案对我都不起作用。

EDIT : I added a second snippet, if you want to log and return the real result of your async call. 编辑 :如果您想记录并返回异步调用的实际结果,我添加了第二个代码段。 Hope it helps! 希望能帮助到你!

You just miss the async keyword in your arrow function: 您只是错过了箭头函数中的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; 

I could not test that but it is syntactically correct. 我无法测试,但是在语法上是正确的。

Second possibility to return the finak result : 返回finak结果的第二种可能性:

 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; 

Not tested but should work. 未经测试,但应该可以。 Try setting the context explicitly 尝试显式设置上下文

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

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

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

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