如何使JS堆栈真正“等待”为了结束异步功能?

发布于 2025-02-11 05:52:10 字数 811 浏览 0 评论 0原文

我正在学习异步JavaScript的工作原理,并且正在尝试将数字1和2(按此顺序)打印出来。 logs 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

我做错了什么?

I'm learning how Asynchronous JavaScript works, and I'm trying to print to the console the numbers 1 and 2 (in this order). The function that logs 1 has a setTimeout, and as such, the order is always inverted. I know why this happens. I just don't know how to make it work as I would like to. I've tried this:

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()

and also this:

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()

Both of which print

running...
2
1

The desired output would be

running...
1
2

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

み格子的夏天 2025-02-18 05:52:10

回调是不可接受的吗?

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.");

Would callbacks not be acceptable?

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.");

白况 2025-02-18 05:52:10

阅读有关JS Promises的了解( )在这里他的代码工作

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()

Read about Js promises (developer.mozilla.org) here his your code working

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()

满意归宿 2025-02-18 05:52:10

谢谢你们的反馈。我向您的答案投票,因为他们俩都帮助我解决了这个问题,并帮助我对手头上的问题有了更高的了解(但是因为我在这里仍然是新手,所以upvote就像一个承诺一样)。

但是,我觉得他们都没有进入引起问题的具体点。

这是现在注释的工作代码

// 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(/* return a value */) 
                    
        /*  so,  ' (resolve) => ' and then the 
            ' resolve( value ) '
            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 parameters).
 
            And when the code fulfills the promise 
            (by reaching either resolve() or reject()) --- in this case, by reaching 
            ' resolve( value ) ', 
            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(/* return a value */) 
                    
        },
        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

Thank you guys for your feedback. I upvoted your answers as they both helped me solve this issue, and helped me get to a higher understanding of the matter at hand (but because I'm still new here, the upvote is just like a Promise).

However, I feel like none of them has gotten to the SPECIFIC point that was causing the issue.

Here's the commented working code

// 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(/* return a value */) 
                    
        /*  so,  ' (resolve) => ' and then the 
            ' resolve( value ) '
            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 parameters).
 
            And when the code fulfills the promise 
            (by reaching either resolve() or reject()) --- in this case, by reaching 
            ' resolve( value ) ', 
            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)

Now, without callback

// Without Callback, and using .then()

function first(){
     
    return new Promise ( (resolve) =>  setTimeout(()=>{ 
        console.log(1)
        resolve(/* return a value */) 
                    
        },
        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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文