如何修复此代码中的异步函数

时间:2015-12-14 22:11:26

标签: javascript

我有这个javascript代码无法正常工作。

var asyncFunction = function () {

    setTimeout(function () {
        return 'accepted';
    }, Math.floor(Math.random() * 5000));
};
var Applicant;
(Applicant = function (applicant_name_var, applicant_age_var) {
    name = applicant_name_var;
    a = applicant_age_var;
    return {
        who_AM_I: function () {
            if (name == null) { return 'No Name'; }
            else {
                return name;
            }
        },
        isAdult: function () {
            if (a == null) {
                return false;
            } else
                if (a < 18) {
                    return false;
                } else {
                    return true;
                }
        },
        INTERVIEWRESULT: function () {
            var result = 'pending';
            result = asyncFunction();
            return result;
        }
    };
}).call();
console.log('debut');
var pending_APPLICANT = [];
var accepted_APPLICANT = [];
var applicant1 = new Applicant('John Doe');
var applicant2 = new Applicant();
var applicant3 = new Applicant('Jane Doe', 24);
pending_APPLICANT.push(applicant1);
pending_APPLICANT.push(applicant2);
pending_APPLICANT.push(applicant3);
if (applicant1.INTERVIEWRESULT() == 'accepted') {
    accepted_APPLICANT.push(applicant1);
    pending_APPLICANT.splice(1, 2);
}
if (applicant2.INTERVIEWRESULT() == 'accepted') {
    accepted_APPLICANT.push(applicant2);
    pending_APPLICANT.splice(1, 1);
}
if (applicant3.INTERVIEWRESULT() == 'accepted') {
    accepted_APPLICANT.push(applicant3);
    pending_APPLICANT.splice(0, 1);
}
console.log('Pending applicants:');
for (var i = 0; i < pending_APPLICANT.length; i++) {
    console.log(pending_APPLICANT[i].toString());
}
console.log('Accepted applicants:');
for (var i = 0; i < accepted_APPLICANT.length; i++) {
    console.log(accepted_APPLICANT[i].toString());
}

此代码的输出为:

> debut

> Pending applicants:

> [object Object]

> [object Object]

> [object Object]

> Accepted applicants:

预期的输出是这样的:

> Pending applicants:

> No one.

> Accepted applicants:

> Name: Jane Doe | Age: 24 | Adult: true

> Name: John Doe | Age: Unknown | Adult: false

> Name: No Name | Age: Unknown | Adult: false

我认为问题出在asyuncFunction()

1 个答案:

答案 0 :(得分:0)

此:

var asyncFunction = function () {

    setTimeout(function () {
        return 'accepted';
    }, Math.floor(Math.random() * 5000));
};
result = asyncFunction();

不会做你期望的事。

您无法返回在异步任务中确定的内容。

请查看this question

您可以做的是将回调函数传递给asyncFunction,并在解析时将其调用为所需的值。

var asyncFunction = function (cb) {
    setTimeout(function () {
        cb('accepted');
    }, Math.floor(Math.random() * 5000));
};

它需要对您的代码进行更多更改,但您明白了。

以下是您在代码中使用该功能的方法:

asyncFunction(function (result) {
    console.log(result); //accepted
});