如何将XHR.onload中的数据返回至makeCorsRequest主函数?
嘿,你这碰到的是异步操作的典型坑点呀!我来给你捋捋为啥现在的写法行不通,再给你几个靠谱的解决方案。
为什么直接return没用?
XHR请求是异步执行的——当你调用xhr.send()后,JavaScript不会等着请求完成,而是直接继续执行后面的代码,所以makeCorsRequest函数会在请求完成前就执行完毕,返回undefined。而xhr.onload里的return text,只是在这个回调函数内部返回值,根本传不到外层的makeCorsRequest里。
解决方案1:使用回调函数
这是比较传统的异步处理方式,给makeCorsRequest加一个回调参数,在请求完成时调用这个回调把数据传出去:
makeCorsRequest(email, callback) { var xhr = this.createCORSRequest(email); xhr.onload = function() { var text = xhr.responseText; // 成功时把数据传给回调,第一个参数是错误(null表示无错误) callback(null, text); }; // 别忘了处理请求失败的情况 xhr.onerror = function() { callback(new Error('CORS请求失败'), null); }; xhr.send(); } // 调用的时候这么用: this.makeCorsRequest('your-email@example.com', function(error, data) { if (error) { console.error('请求出问题啦:', error); return; } console.log('拿到的数据:', data); // 在这里处理你拿到的数据就好 });
解决方案2:使用Promise(推荐)
用Promise把异步请求包装起来,这样可以用更清晰的链式调用或者async/await来处理结果,这也是现在更主流的异步处理方式:
makeCorsRequest(email) { return new Promise((resolve, reject) => { var xhr = this.createCORSRequest(email); xhr.onload = function() { var text = xhr.responseText; // 请求成功时,把数据resolve出去 resolve(text); }; xhr.onerror = function() { // 请求失败时,把错误reject出去 reject(new Error('CORS请求失败')); }; xhr.send(); }); } // 调用方式1:用.then()链式调用 this.makeCorsRequest('your-email@example.com') .then(data => { console.log('拿到的数据:', data); // 处理数据 }) .catch(error => { console.error('请求出错:', error); }); // 调用方式2:用async/await(需要在async函数内使用) async function handleRequest() { try { const data = await this.makeCorsRequest('your-email@example.com'); console.log('拿到的数据:', data); // 处理数据 } catch (error) { console.error('请求出错:', error); } } handleRequest();
这样就能把xhr.onload里拿到的数据,正确传递到需要使用它的地方啦。
内容的提问来源于stack exchange,提问作者Gustavo
相关产品推荐
相关产品推荐

