2017-02-18 40 views
0

我有這樣的代碼時:試圖數據推到我的數組爲保證這不保存數據

let splatshArtData = []; 
splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl);     
}); 
console.log(splatshArtData); 

我要添加「splatshArtUrl」我的陣列,但是這不工作,當我嘗試打印數據,這不會打印什麼,我不知道該怎麼做,任何想法?異步函數getSplatchArt解決它的承諾之後

let splatshArtData = []; 
splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl); 
    console.log(splatshArtData);     
}); 

的功能then運行裏面,所以它運行的console.log項目被添加到陣列之前:

+0

'.save'方法是什麼? –

+0

@ Alexandru-IonutMihai哦,沒什麼,髒的代碼:p –

+1

將'console.log(splatshArtData);'移到'.then()'塊中,它會起作用。你的函數調用是異步的,但你認爲它是同步的,因此是錯誤。 –

回答

0

試試這個。

+0

這不是真的正確。當然這是有效的,但'.then()'中的函數顯然不會在異步函數*之後運行。它會在'getSplatchArt'返回的許諾得到解決時運行,其中*可能恰好在之後,但也可能在10分鐘後。 –

+0

我不想迷惑他,因爲他似乎不明白承諾會做什麼。 –

+0

那麼,你應該清楚它的工作原理,因爲你現在所說的答案是不正確的。 –

0

你在這裏面臨的問題是getSplatchArt返回一個承諾,並承諾需要時間來解決。因此,您不能保證splatshArtData.push(splatshArtUrl);將在console.log之前運行。

解決方案是將所有需要從promise中返回的數據的邏輯移到promise回調中。這當然可以包括對其他功能的調用。

// function to process the splashArtData - will be called from the promise 
// when the promise is resolved. 
function processSplashArt(data) { 
    // this will now print as you are expecting 
    console.log(data); 
} 

let splatshArtData = []; 

splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
    splatshArtData.push(splatshArtUrl);  

    // pass the splashArtData to the callback function - it's now ready 
    processSplashArt(slashArtData);   
}); 
0

JavaScript是同步的,因此每行代碼都會一個接一個執行。

如果我們註釋行號代碼像下面

1. let splatshArtData = []; 
2. splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
3.  splatshArtData.push(splatshArtUrl);     
    }); 
4. console.log(splatshArtData); 

你假設它會在1,2,3,4的順序運行,而在現實中,它會在順序運行1,2,4,3爲什麼?因爲JavaScript是同步的,並且第2行中的函數是異步的,這意味着在繼續之前您必須等待。如果您沒有將splatshArtData變量設爲空數組,因爲尚未提取數據。

如果你想返回提取的數據並在另一個函數中使用它,你不應該混合它將回調建議在另一個答案,而是諾言和使用從獲取函數的解析值數據。

function getSplatshArt() { 
    let splatshArtData = []; 

    //Return a promise 
    return splatshArt.getSplatchArt(participants[i].championId).then((splatshArtUrl) => { 
     console.log(splatshArtData); //this will log out the data 
     splatshArtData.push(splatshArtUrl); 
     return splatshArtData; //this will be the resolved value from the promise 
    }); 
} 

//Call the function and access the resolved data in the .then() block 
getSplatshArt() 
    .then(data => { 
     console.log(data); //this is the data returned from the getSplatshArt function 
    }); 

看你的代碼,我開始覺得你是遍歷ID的數組的印象,如果你想一次取多個值,這不會工作,因爲你必須處理多個承諾。但那是另一個問題,我想你應該在詢問這個問題之前,先對自己的問題做更多的研究。