Solve the problem that JavaScript XHR returns null prematurely

Original link: https://hsiaofeng.com/archives/228.html

In XHR, due to the asynchronous feature, the variable is return before being assigned, and the return value will be empty at this time.

solution

Put the part that sends the XHR in the function xhrReq() and use Promise . Use reslove() in the onload part to return the result, and use reject() in onerror part to return the failure result.

 function xhrReq() { return new Promise(function(reslove, reject) { //... let req = new XMLHttpRequest(); req.onload = function () { //... reslove(return_text) } req.onerror = function(){ reject(req.statusText); } //req.send(...); } ) }

Then use async before the function that needs to be called, and add await at the call.

 async function main(){ //... let ret = await xhrReq(); //.. }

This article is transferred from: https://hsiaofeng.com/archives/228.html
This site is only for collection, and the copyright belongs to the original author.