Promise和then关键字的使用

tech2026-02-10  2

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); } }); }
最新回复(0)