【问题标题】:Promise and await Javascript承诺并等待 Javascript
【发布时间】:2018-08-27 08:06:10
【问题描述】:

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

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

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 之前查找 item.longDesc(只是我的猜测)。
请帮忙

【问题讨论】:

  • 您确定Item.find().exec() 方法返回Promise 吗?乍一看文档,它需要一个回调。
  • @Sirko await 实际上会通过返回它来处理非承诺值。
  • @UncleDave 我认为他的意思是它可能是一个回调函数而不是一个承诺函数,但我不确定这里的情况。可能是 getItem 实际上没有找到该项目,或者其他一些 API 滥用
  • 啊,真的。如果exec 期待回调,那么await 不会为您做任何事情。
  • 无关:@Terry Smith:lineMessages != [] 可以更优雅地表达为lineMessages.length

标签: javascript node.js mongoose async-await ecmascript-2017


【解决方案1】:

当您需要 mongoose 时,您可以将原生 es6 Promise 传递给 mongoose 选项,然后您可以使用原生 Promise 代替 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 

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

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 并使用异步等待。

【讨论】:

  • 它仍然是undefined
  • 你确定 this.getItem(postback.id) 调用 getItem(id) 方法?
  • 试试这个:更改 getItem 函数:return Item.find({_id: id}); 并将 exec 添加到 let item = await this.getItem(postback.id).exec();
  • 通过记录,lineMessages 似乎没有等待该项目。我不知道为什么。
  • 你确定在 Item.model.js 中,在要求 mongoose 之后,你将原生承诺传递给 mongoose.Promise? const mongoose = require('mongoose'); mongoose.Promise = Promise; ... define schema and model, export
【解决方案2】:

原来 mongoose findOne() 返回一个包含单个对象的数组,而不仅仅是一个对象。

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 2016-11-29
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2019-04-29
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多