Promise返回NodeJS中未定义的

时间:2019-06-09 17:38:46

标签: node.js azure-cosmosdb-mongoapi

我试图在ES6的NodeJS中与Azure Cosmos DB(mongo API)建立连接。回调样式仍然存在,因为我无法在ES6中找到示例(但是在ES7中)。
db.js

export function ReadAll (dbName, collectionName) {
  return ConnectToCollection(dbName, collectionName).then(collection => {
    collection.find({}).then(docs => {
      // docs is not undefined here
      return docs
    })
  })
}

function ConnectToCollection (dbName, collectionName) {
  return new Promise((resolve, reject) => {
    mongoClient.connect(
      PRIMARY_CONNECTION_STRING,
      { useNewUrlParser: true },
      (err, client) => {
        if (err) reject(new Error(err))
        const db = client.db(dbName)
        const collection = db.collection(collectionName)
        resolve(collection)
      }
    )
  })
}

index.js中被调用

app.get('/users', (req, res) => {
  ReadAll(DB_NAME, COLLECTION_NAME_TEMP).then(docs => {
    // but docs here is undefined
    ...
  })
})

我也仍然得到未定义的docs

export function ReadAll (dbName, collectionName) {
  return ConnectToCollection(dbName, collectionName).then(collection => {
      // Even with a return here
      return collection.find({}).toArray(docs => {
        return docs
    })
  })
}

为什么我在这里得到未定义的docs

2 个答案:

答案 0 :(得分:0)

    export function ReadAll (dbName, collectionName) {
  return ConnectToCollection(dbName, collectionName).then(collection => {
    **return** collection.find({}).then(docs => {
      // docs is not undefined here
      return docs
    })
  })
}

希望通过这种方式,您一无所获就可以找到您的文档。

答案 1 :(得分:0)

Shailesh Jha的答案在一半。您需要返回collection.find的结果以不破坏承诺链。您还需要在toArray之后调用find方法,因为该方法返回的游标本身不会在不调用toArray的情况下返回任何项目。因此,您的ReadAll方法应如下所示:

function ReadAll(dbName, collectionName) {
    return ConnectToCollection(dbName, collectionName).then(collection => {
        // add toArray method to actually return items
        collection.find({}).toArray().then(docs => {
            // docs is now returned
            return docs
        })
    })
}