异步任务完成后获取回调

时间:2016-07-23 09:24:47

标签: node.js mongodb asynchronous mongoose

我正在为我的应用创建一个基本的迁移类。

// commands/migrate.js
const Question = require('../models/Question');

class Migrate
{
    constructor() {

    }

    run() {
        console.log("Deleting entries...");

        Question.remove({}, (err) => {
            if (err) {
                throw err;
            }

            console.log("Entries deleted. Seeding...");

            for (var i = 0; i <= 20; i++) {
                new Question({
                    id: i,
                    title: "Who are you?",
                    answers: [
                        "Answer 1",
                        "Answer 2",
                        "Answer 3",
                        "Answer 4"
                    ],
                    correctAnswer: 0
                }).save((err, entry) => {

                    if (err) {
                        throw err;
                        return;
                    }

                    console.log(entry.id + "seeded!");
                });
            }
        });
    }
}

module.exports = () => {
    return new Migrate()
}

我的server.js看起来像这样。

if (typeof process.argv[2] !== "undefined") {
    switch (process.argv[2]) {
        case "migrate":
            require('./commands/' + process.argv[2] + '.js')().run()
            break;

        default:
            throw new Error("Invalid command.");
    }

    return;
}

Question模型依赖于Mongoose。现在我得到以下控制台日志。

Deleting entries...
Entries deleted. Seeding...
0 seeded!
...
20 seeded!

但是,当任务完成时,我想在底部再添加一行,所以它看起来像这样。

Deleting entries...
Entries deleted. Seeding...
0 seeded!
...
20 seeded!
Command successful. Process exiting. // process.exit(0)

有没有办法做到这一点?我应该在上次查询成功完成时抛出回调吗?

1 个答案:

答案 0 :(得分:0)

您可以在包含

的行之后添加if语句

console.log(entry.id + "seeded!");

if (entry.id === 20) console.log('Command successful. Process exiting.');