<repo_name>Trendyol-Front-End-Bootcamp/trendyol-frontend-bootcamp-js-201-202<file_sep>/5-promise-api/8-resolve.js
const fetch = require("node-fetch");

let cache = new Map();

const getUserName = () => {
  if (cache.has("name")) {
    return Promise.resolve(cache.get("name"));
  }

  return fetch(`https://api.github.com/users/enginustun`)
    .then((res) => res.json())
    .then((user) => {
      cache.set("name", `from cache: ${user.name}`);
      return user.name;
    });
};

getUserName().then((name) => {
  console.log({ name });

  getUserName().then((name) => {
    console.log({ name });
  });
});
<file_sep>/4-promise/4-promise-finally.js
function getUserComments(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([
        { id: 1, content: "hello world!" },
        { id: 2, content: "hello bootcamp!" },
      ]);
    }, 1500);
  });
}

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ id: 1, name: "engin" });
    }, 1000);
  });
}

function setLoading(isLoading) {
  if (isLoading) {
    console.log("comments are loading...");
  } else {
    console.log("comments are loaded");
  }
}

setLoading(true);
getUser(1).then((user) => {
  getUserComments(user.id)
    .then((comments) => {
      console.log(comments);
    })
    .catch(() => {})
    .finally(() => setLoading(false));
});
<file_sep>/3-callbacks/1-settimeout.js
function anotherFunc() {
  console.log("<NAME>");
}

function logWithDelay() {
  anotherFunc();
  
}

setTimeout(logWithDelay, 2000);
console.log("<NAME>");

/**
 *  callstack        callback queue        web api / cpp api
 *
 *                                                          
 *
 *    
 *
 *  
 *      
 *  
 * 
 *  
 */
<file_sep>/1-try-catch/5-works-sync-2.js
setTimeout(function () {
  try {
    noSuchVariable; // try...catch handles the error!
  } catch {
    console.log("error is caught here!");
  }
}, 1000);
<file_sep>/5-promise-api/1-all.js
Promise.all([
  new Promise((resolve) => setTimeout(() => resolve(1), 3000)), // 1
  new Promise((resolve) => setTimeout(() => resolve(2), 2000)), // 2
  new Promise((resolve) => setTimeout(() => resolve(3), 1000)), // 3
]).then(console.log); // 1,2,3 when promises are ready: each promise contributes an array member
<file_sep>/1-try-catch/6-error-object.js
try {
  lalala; // error, variable is not defined!
} catch (err) {
  console.log(err.name); // ReferenceError
  console.log(err.message); // lalala is not defined
  console.log(err.stack); // ReferenceError: lalala is not defined at (...call stack)

  // Can also show an error as a whole
  // The error is converted to string as "name: message"
  console.log(err); // ReferenceError: lalala is not defined
}
<file_sep>/6-microtasks/1-microtasks.js
let promise = Promise.resolve();

setTimeout(() => {
  console.log("I am finished first?");
}, 0);

promise.then(() => console.log("promise done!"));

setTimeout(() => {
  console.log("I am finished last");
}, 0);

console.log("hello bootcamp 1");
console.log("hello bootcamp 2");
console.log("hello bootcamp 3");
console.log("hello bootcamp 4");
console.log("hello bootcamp 5");

// setTimeout(() => {
//   console.log("Middle log");
// }, 0);

console.log("hello bootcamp 6");
console.log("hello bootcamp 7");
console.log("hello bootcamp 8");
console.log("hello bootcamp 9");
console.log("hello bootcamp 10");

for (let i = 0; i < 1000000000; i++) {
  const x = Math.random();
}
<file_sep>/7-async-await/1-async-await.js
async function f() {
  return 1;
}

f().then(console.log); // 1
<file_sep>/1-try-catch/3-runtime-error.js
try {
  {{{{{{{
} catch (err) {
  alert("The engine can't understand this code, it's invalid");
}<file_sep>/8-generators/2-generators-2.js
function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

let it = generateSequence();

let one = it.next();

console.log(one, it.next(), it.next(), it.next()); // {value: 1, done: false}

// for (const value of generateSequence()) {
//   console.log(value);
// }
<file_sep>/4-promise/3-promise-error.js
function getUserComments(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error("Boyle user olmaz olsun"));
      resolve([
        { id: 1, content: "hello world!" },
        { id: 2, content: "hello bootcamp!" },
      ]);
    }, 1500);
  });
}

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ id: 1, name: "engin" });
    }, 1000);
  });
}

getUser(1).then((user) => {
  getUserComments(user.id)
    .then((comments) => {
      console.log(comments);
    })
    .catch((err) => {
      console.log(err);
    });
});

setTimeout(() => {
  console.log("cok gec calisacagim");
}, 5000);
<file_sep>/1-try-catch/12-rethrow-2.js
function readData() {
  let json = '{ "age": 30 }';

  try {
    // ...
    blabla(); // error!
  } catch (err) {
    // ...
    if (!(err instanceof SyntaxError)) {
      throw err; // rethrow (don't know how to deal with it)
    }
  } finally {
    console.log("Finally");
  }
}

try {
  readData();
} catch (err) {
  console.log("External catch got: " + err); // caught it!
}
<file_sep>/1-try-catch/11-rethrow.js
let json = '{ "age": 30 }'; // incomplete data
try {
  let user = JSON.parse(json);

  if (!user.age) {
    throw new SyntaxError("Incomplete data: no name");
  }

  blabla(); // unexpected error

  console.log(user.name);
} catch (err) {
  if (err instanceof SyntaxError) {
    console.log("JSON Error: " + err.message);
  } else {
    throw err; // rethrow (*)
  }
}
<file_sep>/7-async-await/7-async-await-error-handling.js
const fetch = require("node-fetch");

async function f() {
  try {
    let response = await fetch("/no-user-here");
    let user = await response.json();
  } catch (err) {
    // catches errors both in fetch and response.json
    console.log(err);
  }
}

f();

// // top-level caselerinde
// async function f2() {
//   let response = await fetch("/no-user-here");
// }
// // f2() becomes a rejected promise
// f2().catch(console.log); // TypeError: failed to fetch // (*)
<file_sep>/7-async-await/6-async-await-class-methods.js
class Waiter {
  async wait() {
    return await Promise.resolve("I am waiting");
  }
}

new Waiter().wait().then(console.log); // 1 (this is the same as (result => console.log(result)))
<file_sep>/4-promise/1-promise.js
const logAfterSomeTime = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Zamani geldiginde calisacagim");
    }, ms);
  });
};

logAfterSomeTime(2000).then((message) => console.log(message));

console.log("<NAME>");
<file_sep>/1-try-catch/15-global-error-handling.js
// window.addEventListener('error', function(event) { ... })
process.on("uncaughtException", function (err) {
  console.log("Caught exception: ", err.name, err.message, err.stack);
});

setTimeout(function () {
  console.log("This will still run.");
}, 1000);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log("This will not run.");
<file_sep>/5-promise-api/2-all-2.js
const fetch = require("node-fetch");
let urls = [
  "https://api.github.com/users/enginustun",
  "https://api.github.com/users/remy",
  "https://api.github.com/users/jeresig",
];

// map every url to the promise of the fetch
let requests = urls.map((url) => fetch(url));

// Promise.all waits until all jobs are resolved
Promise.all(requests).then((responses) =>
  responses.forEach((response) =>
    console.log(`${response.url}: ${response.status}`)
  )
);
<file_sep>/8-generators/4-generators-4.js
let range = {
  from: 1,
  to: 5,

  *[Symbol.iterator]() {
    // a shorthand for [Symbol.iterator]: function*()
    for (let value = this.from; value <= this.to; value++) {
      yield value;
    }
  },
};

console.log(range, [...range]);

for (const val of range) {
  console.log(val);
}
<file_sep>/4-promise/9-promise-error-handling-3.js
// rethrowing

// the execution: catch -> catch
new Promise((resolve, reject) => {
  throw new Error("Whoops!");
})
  .catch(function (error) {
    // (*)

    if (error instanceof URIError) {
      // handle it
    } else {
      console.log("Can't handle such error");

      throw error; // throwing this or another error jumps to the next catch
    }
  })
  .then(function () {
    /* doesn't run here */
  })
  .catch((error) => {
    // (**)

    console.log(`The unknown error has occurred: ${error}`);
    // don't return anything => execution goes the normal way
  });
<file_sep>/1-try-catch/8-json-parse-error.js
let json = "{ bad json }";

try {
  let user = JSON.parse(json); // <-- when an error occurs...
  console.log(user.name); // doesn't work
} catch (err) {
  // ...the execution jumps here
  console.log(
    "Our apologies, the data has errors, we'll try to request it one more time."
  );
  console.log(err.name);
  console.log(err.message);
}
<file_sep>/1-try-catch/1-no-error.js
try {
  console.log("Start of try runs"); // (1) <--

  // ...no errors here

  console.log("End of try runs"); // (2) <--
} catch (err) {
  console.log("Catch is ignored, because there are no errors"); // (3)
}
<file_sep>/1-try-catch/7-json-parse.js
let json = '{"name":"Engin", "age": 30}'; // data from the server

let user = JSON.parse(json); // convert the text representation to JS object

// now user is an object with properties from the string
console.log(user.name); // Engin
console.log(user.age); // 30
<file_sep>/4-promise/8-promise-error-handling-2.js
new Promise((resolve, reject) => {
  resolve("ok");
})
  .then((result) => {
    throw new Error("Whoops!"); // rejects the promise
  })
  .catch(console.log); // Error: Whoops!

new Promise((resolve, reject) => {
  resolve("ok");
})
  .then((result) => {
    blabla(); // no such function
  })
  .catch(console.log); // ReferenceError: blabla is not defined
<file_sep>/1-try-catch/9-throw-own-error.js
// no name in data
let json = '{ "age": 30 }'; // incomplete data

try {
  let user = JSON.parse(json); // <-- no errors
  console.log(user.name); // no name!
} catch (err) {
  console.log("doesn't execute");
}
<file_sep>/8-generators/5-generators-5.js
var standard_input = process.stdin;

function* gen() {
  // Pass a question to the outer code and wait for an answer
  let result = yield "2 + 2 = ?";
  while (true) {
    console.log({ result });
    if (result === 4) {
      return "<NAME>!";
    } else {
      result = yield "Patladin";
    }
  }
}

let generator = gen();

let question = generator.next().value; // <-- yield returns the value
console.log(question);

standard_input.on("data", function (data) {
  // User input exit.
  if (data === "exit\n") {
    process.exit();
  } else {
    let result = generator.next(+data); // --> pass the result into the generator
    console.log(result);
    if (result.value === "<NAME>!") {
      process.exit();
    }
  }
});
<file_sep>/4-promise/2-promise-2.js
function getUserComments(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([
        { id: 1, content: "hello world!" },
        { id: 2, content: "hello bootcamp!" },
      ]);
    }, 1500);
  });
}

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ id: 1, name: "engin" });
    }, 1000);
  });
}

getUser(1).then((user) => {
  getUserComments(user.id).then((comments) => {
    console.log(comments);
  });
});
