承诺findOneAsync变量= {“isFulfilled”:false,“isRejected”:false}?

问题描述 投票:6回答:4

利用Bluebird来支持Mongoose,我有一个Promise.map(带有一系列if / else的函数用于循环遍历数组以查看是否存在引用doc,否则创建一个..

将findOneAsync的产品分配给变量,然后将'variable._id'分配给制作中的新文档(主要承诺),控制台记录{"isFulfilled":false,"isRejected":false}

这是一个片段:

for (i=0; i<items.length; i++) {
    var existingItem = Models.Items.findOneAsync({ item: items[i] });
    console.log( "existingItem : ");
    console.log( JSON.stringify(existingItem) );
    console.log( "existingItem._id : " + existingItem._id );

这是一个日志:

existingItem : 
{"isFulfilled":false,"isRejected":false}
existingItem._id : undefined

为什么existingItem变量可能等待Model.Item.findOneAsync ..?

javascript node.js mongoose promise bluebird
4个回答
5
投票

你的问题不是很清楚,但我问你的问题是,为什么existingItem在你找回之后不会等待。

你明白如何使用承诺吗?大多数情况下,您需要使用.then()或其他promise操作函数来获取其已解析的值:

var existingItem = Models.Items.findOneAsync({ item: items[i] });
existingItem.then(function (value) {
    console.log( "existingItem : ");
    console.log( JSON.stringify(existingItem) );
    console.log( JSON.stringify(value); );
    console.log( "existingItem._id : " + existingItem._id );
});

0
投票

我想你想要:

return Promise.each(items, function(item) {
  return Models.Items.findOneAsync({item: item}).then(function(existingItem) {
    console.log("existingItem", existingItem);
  });
});

0
投票

当你开始编写console.logs时,findOneAsync()还没有完成运行。

使事情变得复杂的是,看起来findOneAsync()正在返回一个Promise(状态在你写日志的时候既没有实现也没有被拒绝)。

因此,如果您想存储和记录找到的项目,则需要

  1. 等待Promise使用其qazxsw poi函数解决,并且
  2. 从“已解析的值”中检索找到的项目。 .then()应该将找到的项目对象作为参数传递给它的findOneAsync()函数(即resolve()里面的某个地方会有:findOneAsync())。

假设这一切,这应该工作:

resolve(foundItem);

0
投票

根本原因是,您不会等到操作完成。您在 for (i=0; i<items.length; i++) { var findPromise = Models.Items.findOneAsync({ item: items[i] }); //the next line won't run until findOneAsync finishes findPromise.then(resolveResult => { var existingItem = resolveResult; console.log( "existingItem : "); console.log( JSON.stringify(existingItem) ); console.log( "existingItem._id : " + existingItem._id ); } } 操作完成之前记录。

您可以使用findOnethen等待操作完成。

  • await then
  • Item.findOne({ where: { id: your_id } }) .then(result => console.log(result)) 函数必须以await键为前缀,但此代码更清晰 async
© www.soinside.com 2019 - 2024. All rights reserved.