如何在javascript中使用线程

how to use threads in javascript

本文关键字:线程 javascript      更新时间:2023-09-26

在javascript中,我试图在变量中收集一个响应并打印它。它将打印变量undind,然后打印响应。它将首先打印servicedata=未定义则它将打印从服务器检索到的响应。

var data = get(requiredUrl);
console.log('servicedata ='+jsonstr);

我认为它不是在等待响应并执行下面的语句。为此,我必须使用线程;我如何在javascript中做到这一点?

function get(partenerUrl) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', partenerUrl, true);
    xhr.send(null);
    xhr.onreadystatechange = function() {
        console.log('in onreadystatechange:' + xhr.readyState + 'status'
                + xhr.status);
        if (xhr.readyState == 4 && xhr.status == 200) {
            var arrayOfObjects = eval(xhr.responseText);
            var jsonstr = JSON.stringify(arrayOfObjects)
            console.log('response>>' + jsonstr);
            return jsonstr;
        }
        return NETWORK_CONNECTION_NOT_FOUND;
    }
}

这里有几个错误。变量jsonstr是在get函数中声明的,因此console.log('servicedata ='+jsonstr);调用甚至无法访问它。

但这无论如何都不起作用,因为您是正确的,调用是异步的,因此,行将立即执行。您需要在get函数内部调用console.log。你已经用console.log('response>>' + jsonstr);做了。所以你真的不明白问题出在哪里?

PS-这与线程无关。

两件事,首先你要做

console.log('servicedata ='+jsonstr);

而不是

console.log('servicedata =' + data);

此外,在中进行一个(异步)jax查询

 xhr.open('GET', partenerUrl, true /* The `true` here mean asynchronous`*/);

因此,脚本不会等待xhr.onreadystatechange回调继续,get方法永远不会向您发送任何信息。如果你想获得实际的数据,你必须在xhr.onreadystatechange回调中进行,或者(这是一个糟糕的选择)将异步参数设置为false,但它最终会冻结你的应用程序。