2017-10-16 79 views
0

在我的簡化代碼:Reactjs - 在API調用獲取數據之前,方法返回結果。 (總是空的對象)

static getData(Id) { 
    const data = []; 
    api.getData(lId) 
    .then((Res) => { 
     data.push(Res); 
    }); 
    return data; 
} 

的API端點獲取數據,但它需要一些時間。該方法總是返回[],但如果我把一個console.log(Res),數據在那裏。這意味着該方法返回最初的const data = [];,它不會等到API返回數據。

我該如何解決這個問題?

Regrds

+0

正確使用promise。 'getData'必須返回一個承諾。看到重複。 –

回答

1

有與您的時間這裏有一個問題:

static getData(Id) { 
    const data = []; 
    api.getData(lId) 
    .then((Res) => { 
     data.push(Res); 
    }); 
    return data; <-- Gets returned before the promise resolves/rejects 
} 

如果你需要做額外的處理在你的數據返回給調用者之前 - 在你的例子中,你把它放到一個數組中 - 你會去的需要用另一個Promise包裝:

static getData(Id) { 
    return new Promise((resolve, reject) => { 
     api 
     .getData(Id) 
     .then((Res) => { 
      const data = [] 
      data.push(Res); 
      resolve(data) 
     }) 
     .catch(reject) 
    }) 
} 
1

您應該使用Promise

例如:

static getData(Id) { 
    return new Promise((resolve) => { 
    api.getData(Id) 
     .then((Res) => { 
     resolve(Res); 
     }); 
    }); 
} 

,並使用此方法是這樣的:

getData(15) 
    .then((data) => { 
    console.log(data); 
    }); 
+0

我用Promise,API是一個承諾。 – Adel

+0

是的,你應該使用另一個承諾,因爲API會調用異步。 –

相關問題