2017-07-11 18 views
0

我想访问一个局部变量x在上下文then使用bind但我得到的是x是未定义的。 我正在使用Promise来检索数据。在诺言中访问本地变量然后范围

AJAX调用情况与此功能:

function ajaxCall(){ 
    p = new Promise(function(resolve, reject){ 
    $.ajax({ 
     url: 'http://localhost:9090/bru/struc/arrivals', 
     headers: { 'Authorization' : "Basic " + btoa("BRU:BRU")}, 
     type: "GET", 
     success: function(data, status, xhr) { 
     resolve(data) 
     }, 
     error: function(xhr, textStatus, errorThrown) { 
      xhr = reject 
     } 
    }) 
    }) 
} 

在这里,我想解开的承诺,并指定其值局部变量x

function getColumns(){ 
    var x 
    r = ajaxCall().then(function(result){ 
    this.x.val = result \\result is available here, I can see it 
    console.log(result) 
    }.bind(this)) 
    console.log('Columns retrieved.') 
    return x 
} 

回答

0

尝试。 done而不是。 then

function getColumns(){ 
    var x 
    r = ajaxCall().done(function(result){ 
    this.x.val = result \\result is available here, I can see it 
    console.log(result) 
    }.bind(this)) 
    console.log('Columns retrieved.') 
    return x 
}