0

I know this has been explained before but I can not get it to work in my code. I also read that XMLHttpRequest was being deprecated. If so can someone please explain how to do this correctly.

function readObject(file)
{
    var verticesCoord = new Array();
    var normalCoord = new Array();
    var textureCoord = new Array();
    var faceCoord = new Array();
    var objFile = new XMLHttpRequest();
    objFile.open("GET", file, false);
    objFile.onreadystatechange = function ()
    {
        if(objFile.readyState === 4)
        {
            if(objFile.status === 200 || objFile.status == 0)
            {
                var responseObj = objFile.responseText;
                var lines = responseObj.split(/\r?\n/);
                lines.forEach (line => 
                {
                    switch(line.substring(0,2))
                    {
                        case 'v ':
                            verticesCoord.push(line);
                            break;
                        case 'vn':
                            normalCoord.push(line);
                            break;
                        case 'vt':
                            textureCoord.push(line);
                            break;
                        case 'f ':
                            faceCoord.push(line);
                            break;
                    }
                });
            }
        }
        alert(verticesCoord);  // This Works
        objFile.send({vertices: verticesCoord, normal: normalCoord, textureCoord: textureCoord, faces: faceCoord,});
    }
    objFile.send(null);
}

var sphere = readObject('data/test.obj');
alert(sphere); // This returns undefined

This return undefined. Again sorry, this has been asked 100s of times but I'm not getting it. Thanks.

  • Your `readObject` isn't returning anything, thus it defaults to `undefined` – CertainPerformance Dec 24 '18 at 01:53
  • If you wanted `sphere` to be `verticesCoord`, best to have `readObject` return a `Promise` that resolves to `verticesCoord` (easier to use `fetch` with Promises though) – CertainPerformance Dec 24 '18 at 01:55
  • And never ever use `false` for async. It's a horrible practice and deprecated. You should be seeing warnings in browser console regarding the deprecation – charlietfl Dec 24 '18 at 01:56

0 Answers0