2017-11-01 9 views
0

複数のテーブルから特定のユーザーデータが存在することを確認して、同時に呼び出すようにしたいのですが、私はBluebird Promise.Propを以下のように使用しています。 sequelize ORMを使用してデータにアクセスします。Sequelize findOneメソッドを使用してBluebird約束で同時呼び出しを行います。戻り値は未定義

Promise.props({ 
    user: (()=>{ 
    return User.findOne({ 
     where: {username: req.user.username} 

    }); 
    }), 
    comments: (()=>{ 
    return comments.findOne({ 
     where: {username: req.user.username} 

    }); 
    }) 
}).then((result)=> { 
    console.log(result.user.name, result.comments.count); 
}); 

また、ネストされた約束で試しましたが、成功しませんでした。 like

Promise.props({ 
    user: (()=>{ 
    return User.findOne({ 
     where: {username: req.user.username} 

    }).then((user)=>{ 
     console.log(user.name); // even here i am getting undefined 
    }); 
    }), 
    comments: (()=>{ 
    return comments.findOne({ 
     where: {username: req.user.username} 

    }); 
    }) 
}).then((result)=> { 
    console.log(result.user.name, result.comments.count); 
}); 

答えて

1

result.userが定義されていない、またはresult.user.nameが定義されていない場合は、明確ではありません。 私は後者を期待しています。

Promise.propsに2つのキーを持つオブジェクトを渡します。 しかし、両方のキーは機能であり、約束ではありません。だからpromise.propsはその機能を見ています。 結果にはまだ2つの機能があります。

Promise.props({ 
    user: User.findOne({ 
     where: {username: req.user.username} 
    }), 
    comments: comments.findOne({ 
     where: {username: req.user.username} 
    }) 
}).then((result)=> { 
    console.log(result.user.name, result.comments.count); 
}); 

他に良い方法はPromise.allている、またはあなたが、その後

Promise.join(
    User.findOne({ 
     where: {username: req.user.username} 
    }), 
    comments.findOne({ 
     where: {username: req.user.username} 
    }), 
    (user, comment) => { 
    console.log(user.name, comments.count); 
    } 
); 
Promise.joinを使用しているどのように多くの約束を知っていれば試してみてください
0

解決値ではなく、Promiseが返されます。結果は、約束の決議で収集し、それに沿って渡す必要があります。

// collect values in this object 
const values = {}; 
// run all promises 
Promise.all([ 
    model.findOne() 
    .then((val) => { 
    // assign result 1 
    values.val1 = val; 
    return Promise.resolve(); 
    }), 
    model.findOne() 
    .then((val) => { 
    // assign result 2 
    values.val2 = val; 
    return Promise.resolve(); 
    }), 
]) 
.then(() => { 
    // the values will be collected here. 
    console.log(values); 
}); 
関連する問題