在尝试将对象属性分配给另一个变量之前,如何等待对象属性变为可用?

时间:2017-05-03 06:56:16

标签: javascript asynchronous javascript-objects

我尝试将对象属性分配给新的对象属性,但不断收到错误 TypeError:无法读取属性' email' null 但是,当我在console.log()时,一旦对象可用,我知道的同一个电子邮件属性正在执行。我如何使它只有在对象属性可用后才执行我的赋值。以下是我的代码:

getAssessments();

function getAssessments() {
    var DiagnosticUserCombo = [];

    Assessment.find({'end_date': {$ne: null}}, function (err, assessments) {

        for (let i = 0; i < assessments.length; i++) {
            getUser(assessments,i, function (thisUser) {
                createObj(assessments,i,thisUser,function(funky) {
                    pushToArray(funky,assessments.length);
                })
            })
        }
    });

    var getUser = function (assessments,index,thisUser) {
        User.findOne({'_id': assessments[index].user_id}, function (err, currentUser) {
            thisUser(currentUser);
        });
    }

    var createObj =  function (assessments,index,thisUser,cb) {
        var currentDiagnosticUser = {};
        var end_date = moment(assessments[index].end_date).format('DD-MM-YY');
        currentDiagnosticUser.email = thisUser.email;
        currentDiagnosticUser.company = thisUser.company;
        currentDiagnosticUser.job_title = thisUser.job_title;
        currentDiagnosticUser.diagnostic_id = assessments[index]._id;
        currentDiagnosticUser.end_date = end_date;
        cb(currentDiagnosticUser);
    }

    function sendDiagnostic(dl) {

        if (DiagnosticUserCombo.length === dl) {
            DiagnosticUserCombo.sort(sortArray('end_date')).reverse();
            return true;

        }
    }

    function pushToArray(currentDiagnosticUser,test) {
        DiagnosticUserCombo.push(currentDiagnosticUser);
        if (sendDiagnostic(test)) {
            callback(DiagnosticUserCombo);
        }
    }

    function sortArray(prop) {
        var sortOrder = 1;
        if (prop[0] === "-") {
            sortOrder = -1;
            prop = prop.substr(1);
        }
        return function (a, b) {
            var result = (a[prop] < b[prop]) ? -1 : (a[prop] > b[prop]) ? 1 : 0;
            return result * sortOrder;
        }
    }

}

0 个答案:

没有答案