简体   繁体   English

承诺并等待Javascript

[英]Promise and await Javascript

I've got a strange problem.. FIrst, take a look at my code: 我遇到了一个奇怪的问题。首先,看一下我的代码:

This one is where I use my await.. 这是我等待的地方。

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);
                    }
                });

This is the getItem(id) method.. 这是getItem(id)方法。

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

But it turns out the text key on my lineMessage is undefined.. 但是事实证明我的lineMessage上的文本键是未定义的。
Then, the lineMessage is LineMessages: [{"type":"text"}] ( I once logged it on my console) 然后,lineMessage是LineMessages: [{"type":"text"}] (我曾经在控制台上记录过它)
Why await doesn't stop the execution in my case? 为什么在我的情况下等待不停止执行?
It seems it tries to look up item.longDesc before item is resolved (just my guess tho). 看来它试图在解决item之前查找item.longDesc (只是我的猜测)。
Please help 请帮忙

When you require mongoose you can pass native es6 Promise to mongoose options, then you can use native promises instead of mongoose queries 当您需要猫鼬时,可以将本机es6 Promise传递给猫鼬选项,然后可以使用本机Promise代替猫鼬查询

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 

Or on mongoose connection options (globally) 或在猫鼬连接选项上(全局)

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

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

Mongoose queries is pretty weird. 猫鼬查询很奇怪。 Item.find({_id: id}).exec() returs mongoose query, and have .then() method, but its not native js promise! Item.find({_id: id}).exec()还原猫鼬查询,并具有 .then ()方法, 但它不是本机js承诺! When you add custom promiseLibrary to mongoose instance then Item.find({_id: id}).exec() returns native js Promise and work with async await. 当您向猫鼬实例添加自定义promiseLibrary时, Item.find({_id: id}).exec()返回本机js Promise并与异步等待一起工作。

事实证明,猫鼬findOne()返回一个具有单个对象的数组,而不仅仅是一个对象。

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

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