[英]Javascript callback inside promise
我將數據從mongoDB導出到javascript時遇到問題。 因此,我在mongoDB中使用了promises,並且我使用了.toArray()方法來檢索數據。 我正在嘗試將數據傳遞給回調中的下一個.then()。
這是我的代碼:
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/website';
MongoClient.connect(url)
.then((db, err) => { assert.equal(null, err); return [db, err] })
.then(([db, err]) => {
return [db.collection('goodsList'), db];
})
.then(([collection, db]) => {
function toArr(collection) {
var documents = collection.find({}).toArray( function(err, docs) {
return docs;
})
}
return [toArr(collection), db]
})
.then(([docs, db]) => {
console.log(docs)
console.log(db)
db.close()
})
.catch ((err) => {throw err})
它返回未定義和'Db'對象。 我知道代碼已損壞,但我不知道如何解決。
當.toArray
返回一個.toArray
時,您需要重寫代碼以等待該Promise-無需在.then中使用該函數,如下面的代碼所示
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/website';
MongoClient.connect(url)
.then((db, err) => {
assert.equal(null, err);
return [db, err];
})
.then(([db, err]) => {
return [db.collection('goodsList'), db];
})
.then(([collection, db]) =>
// wait for .toArray to resolve then return [docs, db]
collection.find({}).toArray()
.then(docs => [docs, db])
)
.then(([docs, db]) => {
console.log(docs)
console.log(db)
db.close()
});
代碼的最后一行
.catch ((err) => {throw err}) // no need for this
是多余的,實際上與完全沒有該代碼相同!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.