Javascript 如何使javascript fetch 同步?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44735669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:42:48  来源:igfitidea点击:

How to make javascript fetch synchronous?

javascriptjsonasynchronousfetch-api

提问by Nabeel Khan

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.

我正在使用 fetch 从 api 获取数据 json。工作正常,但我必须在各种调用中重复使用它,因此它需要同步,否则我需要某种方式在每个组件的提取完成时更新界面。

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 ?

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

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

Thanks

谢谢

Edit

编辑

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.

问题是关于 fetch-api,不是 ajax,不是 jquery,所以请不要在没有正确阅读的情况下将其标记为这些问题的重复。如果你仍然觉得有必要这样做,请停止将它与十年前的问题和答案联系起来,十年后会有很多变化。

回答by Jonas Wilms

You want your fetch function to return sth:

你想让你的 fetch 函数返回某个东西:

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);
    });    
}

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

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

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


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

如果你想要一些花哨的 ES7,你可以像这样重写整个事情:

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);
})()