首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JS中访问父函数的变量然后阻塞

如何在JS中访问父函数的变量然后阻塞
EN

Stack Overflow用户
提问于 2018-07-28 03:00:03
回答 1查看 475关注 0票数 -1

我需要从外部函数中声明的then块内部访问一个变量,但由于某种原因,其中一些变量显示为未定义。是否有特定的名称可以在then的作用域内访问?

function foo(tableIDs, tableID, fieldID)
{
    var tables = new Array();
    var bar = new Array();
    var zim = new Array();
    var gir = new Object();

    zim.push(fieldID);
    gir.id = fieldID;

    otherFunction(tableID).then(function(response)
    {
         tables.push(response); // works fine
         bar.push(response); // bar is undefined
         zim.push(response); // zim is undefined
         gir.response = response; //gir is undefined
    });
}

此外,虽然可以在then语句中访问tableID,但tableID和fieldID都不能。目前,我正在通过将fieldID推入表中并在处理响应之前以这种方式访问它来“解决”这个问题,但这似乎是一个我想要避免的非常丑陋的解决方案。由于表和bar之间的唯一区别是变量的名称,因此上面示例中使用的所有名称都是我在处理此问题时使用的名称。

EN

回答 1

Stack Overflow用户

发布于 2018-07-28 03:17:57

你的代码运行的很好。出于测试目的,我已经完成了您的实现,并且运行良好。检查它:

function otherFunction(tableID){
  return new Promise(function(resolve,reject){
    resolve(tableID)
  })
}
  

function foo(tableIDs, tableID, fieldID){
    var tables = new Array();
    var bar = new Array();
    var zim = new Array();
    var gir = new Object();

    zim.push(fieldID);
    gir.id = fieldID;

    otherFunction(tableID).then(function(response){
         tables.push(response); 
         bar.push(response); 
         zim.push(response); 
         gir.response = response; 
         
         console.log('response:',response)
         console.log('tables:',tables)
         console.log('bar:',bar)
         console.log('zim:',zim)
         console.log('gir:',gir)
         console.log('tableIDs:',tableIDs)
         console.log('tableID:',tableID)
         console.log('fieldID:',fieldID)

    });
}

foo('test-tableIDs' , 'test-tableID', 'test-fieldID')

向foo()传递参数或在Promise函数中传递参数时一定有错误...

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51564023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档