こんにちは私の関数をcallbackからpromiseに変換しようとしています。
すべての投稿に追加したいと思っています。post.authorNameフィールドを経由してforEachループにアクセスし、にユーザリストを照会してください。
最初に私はコールバックを試みましたが、これはasyncであり、syncツールが必要です。
私はpromiseを使用しますが、依然として私の結果はコールバックのようです。
これは私のコードです:node.jsの約束と機能を同期させる方法
var mongo = require('mongodb').MongoClient();
var url = "mongodb://localhost:27017/blog";
var ObjectId = require('mongodb').ObjectID;
var listPosts = function(req, res) {
find('post', {}, 10, {author: 1})
.then(function(posts) {
var myPosts = posts;
const promises = [];
myPosts.forEach(function(post) {
console.log("hi i'm forEach" + '\n');
console.log(post);
console.log('\n');
const promise = new Promise(function(resolve, reject){
getPostAuthorName(post.authorID)
.then(function(postAuthor){
post.authorName = postAuthor;
})
resolve();
});
console.log("i'm end of forEach and this is result:");
console.log(post);
console.log('\n');
promises.push(promise);
});
Promise.all(promises).then(() => {
console.log('i should print at end' + '\n');
});
});
}
var getPostAuthorName = function(authorID) {
return new Promise(function(resolve, reject){
findOne('user', {_id: new ObjectId(authorID)})
.then(function(result){
console.log("i'm getPostAuthorName" + '\n');
resolve(result.name);
})
})
}
var find = function(collection, cond = {}, limit = 0, sort = {}) {
return new Promise(function(resolve, reject){
mongo.connect(url)
.then(function(db){
db.collection(collection)
.find(cond).limit(limit).sort(sort).toArray()
.then(function(result){
resolve(result);
})
})
});
}
var findOne = function(collection, cond = {}){
return new Promise(function(resolve, reject){
mongo.connect(url)
.then(function(db){
db.collection(collection).findOne(cond)
.then(function(result){
console.log("i'm findOne" + '\n');
resolve(result);
})
})
})
}
listPosts();
と終了時に、私はこの結果を受け取る:
hi i'm forEach
{ _id: 59888f418c107711043dfcd6,
title: 'FIRST',
content: 'this is my FIRST post',
timeCreated: 2017-08-07T16:03:13.552Z,
authorID: '5987365e6d1ecc1cd8744ad4' }
i'm end of forEach and this is result:
{ _id: 59888f418c107711043dfcd6,
title: 'FIRST',
content: 'this is my FIRST post',
timeCreated: 2017-08-07T16:03:13.552Z,
authorID: '5987365e6d1ecc1cd8744ad4' }
hi i'm forEach
{ _id: 598d60d7e2014a5c9830e353,
title: 'SECOND',
content: 'this is my SECOND post',
timeCreated: 2017-08-07T16:03:13.552Z,
authorID: '5987365e6d1ecc1cd8744ad4' }
i'm end of forEach and this is result:
{ _id: 598d60d7e2014a5c9830e353,
title: 'SECOND',
content: 'this is my SECOND post',
timeCreated: 2017-08-07T16:03:13.552Z,
authorID: '5987365e6d1ecc1cd8744ad4' }
i should print at end
i'm findOne
i'm getPostAuthorName
i'm findOne
i'm getPostAuthorName
関数は同期的に実行しない理由を。 解決策は何ですか?
あなたが特定の質問への問題を軽減し、[MCVE]を提供していただけますか? – PeterMader
あなたはただ1つの質問に答えることができます:**約束**は同期のプログラミングを保証しますか? –
いいえ、もちろんです。プロミスは、非同期に対処するより良い方法です。非同期タスクを同期させないでください。 – PeterMader