Promise和then关键字的使用
异步任务需要多次嵌套的时候,需要互相等待,容易错乱。所以使用Promise和then。
在第一个importCSV
函数里面new Promise
,之后执行里面的参数,等待resolve
返回值,之后再执行_loadCSV
的函数,等待_loadCSV
函数执行到resolve
,在回到第一个importCSV
函数里执行then
,最终完成这个程序。
function importCSV(fileName) {
this._fileName = fileName;
return new Promise(function (resolve, reject) {
_this._loadCSV().then (function (str) {
var arr = [];
}
resolve(arr);
});
});
}
importCSV.prototype._loadCSV = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.open("get", _this._fileName, true);
request.send(null);
request.onload = function(){
resolve(request.responseText);
}
});
}