NodeJS等到功能完成

时间:2018-01-30 15:32:03

标签: javascript node.js

我有一个应用程序,其中我有一个Client类,当我在discord上收到一条消息时,需要为每个用户执行不同的配置(它是一个有自己的API调用的聊天应用程序检查新消息等)。每当我收到带有该用户新配置的新消息时,我都初始化了obj构造函数,但问题是当我同时收到多条消息时,只有最新用户的配置用于创建的所有客户端对象。从应用程序附加示例代码:

等待消息代码:

const app = require("./Client")
const app2 = require("./MyObject")

bot.on('message', async (message) => {

    let msg = message.content.toUpperCase(), pg;
    let client = await new app2.MyObject();

    //set all such configurations
    config.a = "valuea";

    // initialize my 
    pg = await new app.Client(config, client);

    let result = await pg.Main(bot, message, params).then((result) => {
        // Do stuff with result here
    });
});

客户端类:

class Client {

    constructor(config, client) {
        this.config = config;
        this.client = client;
    }

    async Main(bot, message, params) {
        let result = {};
        this.client.setProperty1("prop");
        await this.client.doSOmething();
        result = await this.doSOmethingMore(message);
        this.client.doCleanUp();
        return result;
    }
}

我还试过在Client类中初始化obj构造函数,但即便如此也因为某些原因而失败。

任何建议我如何更正我的代码?

2 个答案:

答案 0 :(得分:2)

您无需同时使用.thenawait

bot.on('message', async (message) => {

    let msg = message.content.toUpperCase();
    let client = await new MyObject();

    //set all such configurations
    config.a = "valuea";

    // initialize my 
    pg = new app.Client(config, client);

    let result = await pg.Main(bot, message, params);
    // Do stuff with result here
    console.log(result);
});

(您不需要在构造函数调用时使用await,因为它不是异步方法)

注意:async-await适用于比7.6更高版本的节点

如果您想使用.then

bot.on('message', (message) => {
    let msg = message.content.toUpperCase();
    new MyObject().then(client => {
        //set all such configurations
        config.a = "valuea";

        // initialize my 
        pg = new app.Client(config, client);

        pg.Main(bot, message, params).then(result => {
            // Do stuff with result here
            console.log(result);
        });
    });
});

答案 1 :(得分:2)

很难确定,因为您不包含MyObject代码,但通常是it's a bad practice to return a promise from a constructor

此外,如果你做得不对,那么任何承诺解决的事实上可能并不是你的调用代码所期望的客户端。

相关问题