2016-07-07 34 views
-1

我想從公共API提取一個數組,我收到的是一個promise。我如何從API中返回數組,在我的函數之外?從公共API提取JSON數據,返回一個承諾

請看看代碼我想實現:

var getMov = function() { 
    return fetch('http://localhost:8080/api/projects') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      JSON.parse(responseJson.movies); 
      return responseJson.movies; 
     }) 
}; 
console.log(getMov()); 

讓我知道如果你有任何想法,如何解決這個問題的承諾。

回答

1

你只需要再次使用then方法。

getMov().then(function(movies) { 
    // do smth with movies 
}); 

按照promises specsonFulfilled函數的自變量將是最後exectuted onFulfilled方法,這是你的情況下返回movies返回值。