我的變數keys出現了問題。getAllKeys將鍵值保存到變數keys中。我想在prepareDate中使用keys,但是當代碼進入prepareDate時,它就無法作業了,因為值還沒有被分配到變數keys中(因為JavaScript Async的原因)
。我需要知道我如何才能等到keys"就緒",從而使prepareDate(以及代碼的其他部分)能夠與keys一起作業。有.then和promise(如果這是正確的解決方案),但我不知道如何在這里使用它們。
let keys = []。
const getAllKeys = async ( ) => {
try {
keys = await AsyncStorage.getAllKeys()。
} catch (e) {
//讀取密鑰錯誤。
}
console.log("keys: ", keys) //span>這是在作業,鍵被保存在鍵里面。
}
const getData = async (key)=> {
try {
const jsonValue = await AsyncStorage.getItem(key)。
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
//錯誤讀取值。
}
};
const prepareData = (/span>) => {
console.log("key: ", keys)
keys.forEach((key) => { // I want that this works but there is nothing inside keys.
console.log(" hier")
console.log(getData(key)))
})
}
getAllKeys()。
prepareData()。
uj5u.com熱心網友回復:
停止使用一個全域變數keys。相反,從一個值(因此,getAllKeys回傳getAllKeys()回傳一個承諾),并接受鍵作為引數給preprateData:
const getAllKeys = async()=> {
try {
return await AsyncStorage.getAllKeys()。
} catch (e) {
//讀取密鑰錯誤。
return [];
}
};
const prepareData = async (keys)=> {
const data = Promise.all(keys。 map(key => {
console.log(key)。
return getData(key)。
}))
console.log(資料)。
return data;
}
現在你可以將它們作為
使用getAllKeys().then(prepareData)。
或者在
(asnyc () => {
const keys = await getAllKeys() 。
console.log("keys: ", keys) // this works
await prepareData(keys)。
})();
uj5u.com熱心網友回復:
你可以把對prepareData的呼叫推遲到getAllKeys完成之后,就像這樣:
getAllKeys的呼叫。
getAllKeys().then(prepareData);
我們可以這樣做,因為getAllKeys是一個異步函式,因此回傳一個Promise,這使得我們可以對它呼叫then-方法。
uj5u.com熱心網友回復:
你可以等待這個承諾:
let keys = []。
const getAllKeys = async ( ) => {
try {
keys = await AsyncStorage.getAllKeys()。
} catch (e) {
//讀取密鑰錯誤。
}
console.log("keys: ", keys) //span>這是在作業,鍵被保存在鍵里面。
}
const getData = async (key)=> {
try {
const jsonValue = await AsyncStorage.getItem(key)。
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
//錯誤讀取值。
}
};
const prepareData = (/span>) => {
console.log("key: ", keys)
keys.forEach((key) => { // I want that this works but there is nothing inside keys.
console.log(" hier")
console.log(getData(key)))
})
}
(async () => {
await getAllKeys()。
prepareData()。
})();
我使用了一個IIFE,因為你不能在一個async函式之外await。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/309141.html
標籤:
上一篇:在目標C中設定變數不當
