如何使javascript同步获取?

问题描述:

我正在使用访存从API获取数据json.工作正常,但我必须反复使用它进行各种调用,因此它需要同步,否则当每个组件的提取完成时,我需要某种方式来更新接口.

I'm using fetch to get data json from an api. Works fine but I have to use it repeatedly for various calls, thus it needs to be synchronous or else I need some way to update the interface when the fetch completes for each component.

function fetchOHLC(yUrl){
    fetch(yUrl)
    .then(response => response.json())
    .then(function(response) {
                alert(JSON.stringify(response.query));

            var t = response.created;
            var o = response.open;
            var h = response.high;
            var l = response.low;
            var c = response.close;

        return {t,o,h,l,c};

    })
    .catch(function(error) {
        console.log(error);
    });    
}

var fetchData = fetchOHLC(yUrl);
alert(fetchData); // empty ?

除了使用fetch之外,还有其他方法可以实现吗? (我不想优先使用jquery).

Is there any other way to achieve it other than using fetch? (I don't want to use jquery preferrably).

谢谢

修改

问题是关于fetch-api,而不是ajax,而不是jquery,因此请在没有正确阅读之前将其标记为这些问题的重复项.而且,如果您仍然感到强迫这样做,请停止将其与十年来一直存在的问题和答案相关联,十年来将有很多变化.

The question is about fetch-api, not ajax, not jquery, so please stop marking it as duplicate of those questions without reading it properly. And if you still feel compelled to do so, please stop linking it to decade old questions and answers, a lot changes in a decade.

您希望您的提取函数返回sth:

You want your fetch function to return sth:

function fetchOHLC(yUrl){
    return fetch(yUrl)
    .then(response => response.json())
    .then(function(response) {
            alert(JSON.stringify(response.query));

        var t = response.created;
        var o = response.open;
        var h = response.high;
        var l = response.low;
        var c = response.close;

    return {t,o,h,l,c};

    })
    .catch(function(error) {
        console.log(error);
    });    
}

现在fetchData包含一个promise,可以很容易地使用它:

Now fetchData contains a promise, which can be easily used:

var fetchData = fetchOHLC(yUrl);
fetchData.then(alert); //not empty ! its {t,o,h,l,c}


如果您想要一些精美的ES7,则可以这样重写整个内容:


If you want some fancy ES7, you could rewrite the whole thing like this:

async function fetchOHLC(yUrl) {
  try {
    const res = await ( await fetch(yUrl) ).json();
    alert(JSON.stringify(r.query));
    return {t:r.created,o:r.open,h:r.high,l:r.low,c:r.close};
  } catch(e) { console.log(e); }
}

(async function () {
  const fetchData = await fetchOHLC(yUrl);
  alert(fetchData);
})()