简体   繁体   中英

Can some please explained this code relating to Js Callback function? I am very confused with this code maybe cause I am a beginner. Questions are:

I am very confused with this code maybe cause I am a beginner. Anyways my questions are:

1.) I did not mention videos anywhere in the code but I did mention video1, video2 and video3 in the array also I wrote a function called getUserVideos. How come in const user when I write getUserVideos(user.userEmail, videos =>{ console.log(videos); }) it automatically shows results?

2.) Why do I need to console.log(user) twice? then again do getUserVideos(user.userEmail, videos =>{ console.log(videos); })?

 console.log('start'); function loginUser(email, password, callback){ setTimeout(() => { callback({ userEmail: email }); },3000); } function getUserVideos(email,callback) { setTimeout(() => { callback (["video1","video2","video3"]); },2000) } const user = loginUser('labeeb@staffasia.org', 123456, user => { console.log(user); getUserVideos(user.userEmail, videos =>{ console.log(videos); }) }); console.log(user); console.log('finish');

A full explanation of the code will be much appreciated.

In a recent Q&A I explained why Promise is the de facto choice for asynchronous control flow in modern JavaScript. Continuation-passing style, as seen in your example, is a wonderful learning exercise but there are many pitfalls and it is very difficult for beginners. This is tagged with promise and async-await so I'll show what the code would look like without continuation-passing style -

 function sleep(ms) { return new Promise(r => setTimeout(r, ms)) } async function loginUser(email, password) { await sleep(3000) return { userEmail: email } } async function getUserVideos (email) { await sleep(2000) return ["video1", "video2", "video3"] } async function main() { console.log("start") const user = await loginUser("labeeb@staffasia.org", 123456) console.log(user) const videos = await getUserVideos(user.userEmail) console.log(videos) return "finish" } main().then(console.log, console.error)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM