[英]How can i change scope of variable
如何更改let result = [];
const Notification = (res) => {
let result = [];
showNotification(notif => notif.map(res => {
result.push(res.date);
console.log(result);
}))
};
此代碼返回日期及其確定
但是當我放這個時,結果返回未定義
const Notification = (res) => {
let result = [];
showNotification(notif => notif.map(res => {
result.push(res.date);
}))
console.log(result);
};
這是一個方法 showNotification,我使用 react-native-push-notification
export const showNotification = (callback) => {
PushNotification.getScheduledLocalNotifications(callback);
}
對不起,我的英語不好
我認為您必須等待回調解決才能獲得結果。 對異步代碼使用 async-await。 讓我知道它是否不起作用。
export const showNotification = async (callback) => {
await PushNotification.getScheduledLocalNotifications(callback);
}
const Notification = async (res) => {
let result = [];
await showNotification(notif => notif.map(res => {
result.push(res.date);
}))
console.log(result);
};
我將假設您所說的“返回”是指變量在控制台中的打印方式,因為您在提供的示例中將console.log
放在了不同的位置。
在第二個結果中打印空數組的原因是因為showNotification
是一個異步 function 接受閉包作為其參數。
簡而言之,function showNotification
中的順序或執行如下所示
result
showNotification
並在調用showNotification
PushNotification.getScheduledLocalNotifications(callback)
后立即返回 showNotification (我認為這是一個異步函數)console.log(result)
打印一個空數組PushNotification.getScheduledLocalNotifcations(callback)
執行傳入的回調 function 並將其附加到捕獲的結果數組中。 在您提供的第二個代碼塊中,雖然console.log(result)
在您調用showNotification()
的行之后,但傳入的閉包以異步方式調用,因此它在執行console.log(result)
之后執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.