我需要从外部函数中声明的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之间的唯一区别是变量的名称,因此上面示例中使用的所有名称都是我在处理此问题时使用的名称。
发布于 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函数中传递参数时一定有错误...
https://stackoverflow.com/questions/51564023
复制相似问题