当前位置:网站首页>JS written test question: asynchronous

JS written test question: asynchronous

2022-06-21 14:27:00 Advanced mathematics volume II half price

const myPromise = Promise.resolve(Promise.resolve("Promise!"));
 
function funcOne() {
 myPromise.then(res => res).then(res => console.log(res));
 setTimeout(() => console.log("Timeout!", 0));
 console.log("Last line!");
}
 
async function funcTwo() {
 const res = await myPromise;
 console.log(await res);
 setTimeout(() => console.log("Timeout!", 0));
 console.log("Last line!");
}
 
funcOne();
funcTwo();
 answer : Last line! Promise! Promise! Last line! Timeout! Timeout!

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1)
}
 
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1)
}
 Print out what ?

 answer : 3 3 3  and  0 1 2

 Asynchronous and let Form a block level scope 

1
Promise.resolve(5)
A: 5
B: Promise {<pending>: 5}
C: Promise {<fulfilled>: 5}
D: Error
 answer :C

promise There are three states ,resolve The corresponding is fulfilled state 

const myPromise = () => Promise.resolve('I have resolved!')
 
function firstFunction() {
  myPromise().then(res => console.log(res))
  console.log('second')
}
 
async function secondFunction() {
  console.log(await myPromise())
  console.log('second')
}
 
firstFunction()
secondFunction()
A: I have resolved!, second and I have resolved!, second
B: second, I have resolved! and second, I have resolved!
C: I have resolved!, second and second, I have resolved!
D: second, I have resolved! and I have resolved!, second
 answer : D

 encounter await myPromise(), It is asynchronous , It blocks the execution of the following code ,
 So first execute firstFunction Medium second, then firstFunction Micro and medium-sized tasks, and then secondFunction The micro task of 

async function getData() {
  return await Promise.resolve("I made it!");
}
 
const data = getData();
console.log(data);
A: "I made it!"
B: Promise {<resolved>: "I made it!"}
C: Promise {<pending>}
D: undefined
 answer :C

 The global execution context calls asynchronously getData after , Then perform console.log. This is the order of execution  getData The result of the call is to return pending State of Promise

原网站

版权声明
本文为[Advanced mathematics volume II half price]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221424598636.html