之前介紹過(guò)這個(gè)作者給的 javascript的語(yǔ)法自測(cè)(數(shù)組)
現(xiàn)在我們聊一聊異步的事情。
async
首先是最外層的測(cè)試,給了一個(gè)回調(diào)done,然后在兩次調(diào)用finish()的時(shí)候,調(diào)用done。
it('you should understand how to use promises to handle asynchronicity', function(done) {
var flag = false;
var finished = 0;
var total = 2;
function finish(_done) {
if (++finished === total) { _done(); }
}
asyncAnswers.async(true).then(function(result) {
flag = result;
expect(flag).to.eql(true);
finish(done);
});
asyncAnswers.async('success').then(function(result) {
flag = result;
expect(flag).to.eql('success');
finish(done);
});
expect(flag).to.eql(false);
});
測(cè)試代碼比較簡(jiǎn)單,需要保證then執(zhí)行的回調(diào)函數(shù)的輸入是async的輸入,所以我新返回了一個(gè)promise,在支持promise的瀏覽器里面是可以測(cè)試通過(guò)的
async: function(value) {
return new Promise(function (resolve) {
resolve(value);
});
},
當(dāng)然也可以通過(guò)語(yǔ)法糖
async: function(value) {
return Promise.resolve(value);
}
作者的答案,利用了Jquery的Deferred
async: function(value) {
var dfd = $.Deferred();
setTimeout(function() {
dfd.resolve(value);
}, 10);
return dfd.promise();
},
manipulateRemoteData
題目要求獲得json數(shù)據(jù),并進(jìn)行name的提取和排序
json數(shù)據(jù)如下
{
"people" : [
{ "name" : "Matt" },
{ "name" : "Rebecca" },
{ "name" : "Paul" },
{ "name" : "Alex" },
{ "name" : "Adam" }
]
}
斷言
it('you should be able to retrieve data from the server and return a sorted array of names', function(done) {
var url = '/data/testdata.json';
asyncAnswers.manipulateRemoteData(url).then(function(result) {
expect(result).to.have.length(5);
expect(result.join(' ')).to.eql('Adam Alex Matt Paul Rebecca');
done();
});
});
我用promise寫(xiě)的代碼
manipulateRemoteData: function(url) {
return Promise.resolve($.ajax(url)).then(function (value) {
var res = [];
var people = value.people;
for(var i=0;i<people.length;i++){
res.push(people[i].name);
}
return res.sort();
})
}
作者給的代碼,用了一下map
manipulateRemoteData: function(url) {
var dfd = $.Deferred();
$.ajax(url).then(function(resp) {
var people = $.map(resp.people, function(person) {
return person.name;
});
dfd.resolve(people.sort());
});
return dfd.promise();
}
};
嘗試一些使用 promise寫(xiě)異步
return new Promise(function (resolve,reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
xhr.open("get","url",true);
xhr.send()
}
})