Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- By now, you've seen that much of JavaScript is based in events. Because our code is running asynchronously, we can't always be sure how long things will take to finish. So far, we've dealt with this using callback functions. A callback is just a function that we call once another procedure is completed. For example, setTimeout is a JavaScript function that takes two arguments, a function and an amount of time in milliseconds. Once that amount of time has gone by, they call the function for us.
- setTimeout(function(){
- console.log("This will be called after two seconds!")
- }, 2000)
- ******************************************************************
- Promises are native javascript objects that wrap around slow procedures. Our promises will respond to a method called then which will fire a function whenever a procedure has finished.
- To start out, we can instantiate a new Promise and pass in a function. This function will take two callback functions as arguments - one for if our procedure works and one for if it doesn't work. We'll refer to these as resolve and reject
- ***********************************************************
- Promises lab
- const questions = [
- {questionText: "Lightning never strikes in the same place twice", answer: false},
- {questionText: "Humans can distinguish between over one trillion different smells", answer: true},
- {questionText: "Goldfish only have a memory of about three seconds", answer: false}
- ]
- let question;
- function appendQuestion(question) {
- let container = document.querySelector('.question-container')
- container.innerHTML = question.questionText
- }
- function askQuestionThen(time) {
- question = questions[0]
- appendQuestion(question)
- return new Promise(function (resolve) {
- setTimeout(function () {
- resolve(question)
- }, time)
- })
- }
- function removeQuestion() {
- return new Promise(function () {
- let container = document.querySelector('.question-container')
- container.innerHTML = ''
- toggleTrueAndFalseButtons()
- })
- }
- function askQuestionThenRemoveQuestion(time) {
- return askQuestionThen(time).then(removeQuestion)
- }
- function trueAndFalseButtons() {
- return btns = document.querySelector('.true-false-list').querySelectorAll('.btn')
- }
- function toggleTrueAndFalseButtons() {
- trueAndFalseButtons().forEach(function (btn) {
- btn.classList.toggle("hide")
- })
- }
- function checkQuestion(question, answer) {
- question.questionAnswer == answer
- }
- function displayQuestionOnClick() {
- let btn = document.querySelector("a");
- return btn.addEventListener("click", () => {
- toggleTrueAndFalseButtons();
- askQuestionThenRemoveQuestion(5000);
- });
- }
Add Comment
Please, Sign In to add comment