2017-04-15 150 views
1

我想在另一個功能完成後運行該功能。我已經找到了實現它的方式,但是我的問題是我想使用getLocation函數的輸出作爲更新函數的參數,在這種情況下是station。在其他功能完成後運行功能

有沒有一種方法可以像這樣運行代碼併爲getLocation函數的輸出分配一個變量?

function giveAddress(){ 
    $.getJSON('http://localhost:5000/api/stations', function(json) { 
     { 
      $.when($.ajax(getLocation(json))).then(function() { 
       update(station); 
      }); 
     }) 
    } 

任何幫助,非常感謝。

+0

是什麼'getLocation'返回的唯一的事情?這是一個承諾嗎? –

+0

它返回一個字符串,站名 – Reggie

+0

''.then''或''.success''或''.error''的名字 –

回答

3

,如果你有承諾不使用回調

function giveAddress(){ 
    return $ 
    .getJSON('http://localhost:5000/api/stations') // first request 
    .then(getLocation) // extract location 
    .then(function(location) { 
     return $.ajax(location) 
     .then(function(){return location}) // second request still return location 
    }) 
    .then(update) 
} 

,或者如果你需要使用越來越location

function giveAddress(){ 
    return $ 
    .getJSON('http://localhost:5000/api/stations') // first request 
    .then(getLocation) // extract location 
    .then(function(location) { 
     return $.ajax(location) 
     .then(function(data){return { 
      location: location, 
      data: data} 
     }) // keep location and data 
    }) 
    .then(function(result) { 
     // use result.data 
     update(result.location) 
    }) 
} 
的結果
+0

道歉,如果這是一個愚蠢的問題,但我怎麼會在這種情況下使用JSON作爲getLocation函數的輸入? – Reggie

+0

@Reggie automagically。 'getJSON'返回Promise-like可執行對象,該對象用來自後端的對象(不是JSON,但已解析)解析。注意我通過'getLocation'本身'.then(getLocation)'。 –

0

你就要成功了,你只需要一個data參數添加到許then回調函數,然後把它傳遞給你的第二個功能:

function giveAddress(){ 
$.getJSON('http://localhost:5000/api/stations', function(json) { 
    { 
     $.when($.ajax(getLocation(json))).then(function (data) { 
      update(data); 
     }); 
    }) 
} 
+0

當我向控制檯輸出「data」變量時,它會打印出頁面,而getLocation函數通常僅將站名打印爲字符串。還有什麼我需要改變? – Reggie

+0

也許你在Web服務中返回了錯誤的結果!? –

0

你需要做的只是採取的應對你的函數的getLocation在承諾。於是(返回),並把它傳遞給更新功能

function giveAddress(){ 
    $.getJSON('http://localhost:5000/api/stations', function(json) { 
    { 
    $.when($.ajax(getLocation(json))).then(function (response) { 
     update(response); 
    }); 
    }) 
} 
相關問題