承诺并等待Javascript

时间:2018-03-18 18:36:34

标签: javascript node.js mongoose async-await es2017

我有一个奇怪的问题.. 首先,看看我的代码:

这是我使用等待的地方..

case "detail": {
                const lineMessages = [];
                let item = await this.getItem(postback.id);
                let lineMessage = {
                        type: "text",
                        text: item.longDesc
                };
                lineMessages.push(lineMessage);
                return new Promise(function(resolve, reject) {
                    if(lineMessages != []) {
                        resolve(lineMessages);
                    }
                    else {
                        let error = new Error("Cannot catch item ${postback.id}");
                        reject(error);
                    }
                });

这是getItem(id)方法..

    getItem(id) {
    return Item.find({_id: id}).exec();
}

但事实证明我的lineMessage上的文本键是未定义的。
然后,lineMessage是LineMessages: [{"type":"text"}](我曾经在我的控制台上记录它)
为什么等待不会停止执行我的情况?
它似乎试图在item.longDesc解决之前查找item(只是我的猜测) 请帮忙

2 个答案:

答案 0 :(得分:0)

当你需要mongoose时,你可以将原生es6 Promise传递给mongoose选项,然后你就可以使用本机promises而不是mongoose查询

const mongoose = require('mongoose');
mongoose.Promise = Promise; // or you can use bluebird. Add this line in models and before connection to database

Item.find({_id: id}).exec() // shoud return native Promise 

或者在mongoose连接选项上(全局)

const options = {
    promiseLibrary: global.Promise
};
mongoose.connect(uri, options);

http://mongoosejs.com/docs/connections.html

Mongoose查询非常奇怪。 Item.find({_id: id}).exec()使用mongoose查询,使用.then()方法,但不是本机js承诺! 当您将自定义promiseLibrary添加到mongoose实例时,Item.find({_id: id}).exec()将返回本机js Promise并使用async await。

答案 1 :(得分:0)

事实证明,mongoose findOne()返回一个包含单个对象的数组,而不只是一个对象。