2015-12-14 51 views
0

我有此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()

+0

*「工作不正常」 *是沒有問題的一個很好的說明?你實際得到了什麼輸出,什麼不起作用 – adeneo

+0

你目前得到的結果是什麼?控制檯中有任何錯誤? – mezmi

+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 
});