我正在學習異步 JavaScript 的作業原理,并嘗試將數字 1 和 2 列印到控制臺(按此順序)。記錄 1 的函式有一個 setTimeout,因此,順序總是顛倒的。我知道為什么會這樣。我只是不知道如何讓它按我的意愿作業。我試過這個:
function first(){
setTimeout(
()=>console.log(1),
1000
)
return Promise.resolve(true)
}
function second(){
console.log(2)
}
function a(){
first()
.then(second())
}
console.log("running...")
a()
還有這個:
async function first(){
setTimeout(
()=>console.log(1),
2000
)
return true
}
function second(){
console.log(2)
}
async function a(){
await first()
second()
}
console.log("running...")
a()
兩者都列印
running...
2
1
所需的輸出將是
running...
1
2
我究竟做錯了什么?
uj5u.com熱心網友回復:
回呼是不可接受的嗎?
function first(callback) {
setTimeout(() => {
console.log(1);
callback();
}, 2000);
}
function second() {
console.log(2)
}
// When first is completed, second will run.
first(() => second());
console.log("This can run at any time, while we're waiting for our callback.");
uj5u.com熱心網友回復:
在此處閱讀有關 Js 承諾(developer.mozilla.org)的資訊,他的代碼正在運行
function first(){
return new Promise((resolve)=>{
console.log('waiting')
setTimeout( ()=>{console.log(1); resolve('waiting finished')}, 2000 )
}
);
}
function second(){
console.log(2)
}
async function a(){
await first().then(res => console.log(res))
second()
}
console.log("running...")
a()
uj5u.com熱心網友回復:
謝謝你們的反饋。我贊成您的回答,因為它們都幫助我解決了這個問題,并幫助我對手頭的事情有了更高的理解(但是因為我還是新手,所以贊成就像一個承諾)。
但是,我覺得他們都沒有達到導致問題的具體點。
這是注釋的作業代碼
// With Callback, Async and Await
async function first(sec){
await new Promise ( (resolve) => setTimeout(()=>{ // this ' (resolve) => ' will make
//sure the Promise is pending until
// the code reaches the
// execution of function resolve()
console.log(1)
resolve(/* do something... */)
/* so, ' (resolve) => ' and then the
' resolve( do something... ) '
are THE MAIN THING.... "await" will only work if
there is a Promise<pending> right in front of it,
and in order to do that we have to create
a Promise object that will receive a resolve() AND/OR reject() as argument
functions. (or whatever function name we want to use for those).
And when the code fulfills the promise
(by reaching either resolve() or reject()) --- in this case, by reaching
' resolve( do something... ) ',
the Promise<pending> will turn to Promise<fulfilled> and this
asynchronous part of the code will, then, continue...
*/
},
2000
))
sec()
}
function second(){
console.log(2)
}
console.log("With callback, async, await ...")
first(second)
現在,沒有回呼
// Without Callback, and using .then()
function first(){
return new Promise ( (resolve) => setTimeout(()=>{
console.log(1)
resolve(/* do something, if you want to... */)
},
2000
))
}
function second(){
console.log(2)
}
console.log("Without callback, and using .then() ...")
first().then(second) // we could also use first().then(()=>second()) if we wanted to
// do something with the returned fulfilled Promise/Response object
// or if we wanted to send the second() function to the
// callback stack before running it
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/498343.html
標籤:javascript 异步 异步等待
