例程中的变量是私有的 - 不能在例程之外调用它 - Javascript

时间:2015-05-06 15:03:31

标签: javascript

如果我提醒这样的标题,标题会被正确警告并且有值。

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 
             alert (title);

        });
   });

如果我提醒这样的标题 - 在例程之外,变量标题为空/未定义。

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 

        });
   });

 alert (title);

我需要在获取例程之外提醒标题。

我尝试在例程中声明变量并为变量提供fetch例程title = fetch(myRequest)......没有任何效果。

我做错了什么?错误在哪里?

注意:我隐藏了此帖子中提取的网址。抓取工作正常。

2 个答案:

答案 0 :(得分:0)

在您的alert(title)电话从Promise链开始后,您的fetch会立即被调用。你的承诺尚未实现。

答案 1 :(得分:0)

这不是关于范围,而是关于计时fetch来电之后的代码在<{strong> 之前运行fetch来电启动完成后,会在调用回调之前运行。

如果您想在其他地方使用title,则需要在回调中调用代码,例如:

var myRequest = new Request('URL');
var title;
fetch(myRequest).then(function(text) {
    return response.text().then(function(text) {
        title= text; 
        doSomethingWithTitle();
    });
});

function doSomethingWithTitle() {
    alert(title);
}

我对你的代码的return response.text().then(...部分感到有些困惑,但是我假设这是正确的,我把它留在了上面。但它真的很可疑。 : - )

相关问题