gpt4 book ai didi

node.js - 回调函数与 Promise 和 Async wait 之间的区别

转载 作者:太空宇宙 更新时间:2023-11-03 22:05:09 25 4
gpt4 key购买 nike

我理解回调函数,但我不理解promise方法和async和await。为什么在node js中使用这三个函数。可以给出示例代码解释。

最佳答案

回调

回调是一个函数,它作为参数传递给另一个函数,并在最后执行。像这样:

function(callback){

//you do some tasks here that takes time

callback();
}

回调是处理异步代码的方法。例如,您可能需要从 Node 应用程序中的文件中读取数据,这个过程需要时间。因此,nodejs 不会在读取时阻塞代码,而是执行其他任务,然后在执行回调后返回。

promise

promise 还可以像回调方法一样处理异步代码,但采用更具可读性的方式。例如,而不是这样:

example(function(){
return example1(function(){
return example2(function(){
return example3(function(){
done()
})
})
})
})

它使它更具可读性,如下所示:

example()
.then(example1)
.then(example2)
.then(example3)
.then(done)

异步函数/等待

async函数用于编写异步代码,特别是promise。在此函数内部,关键字 await 用于暂停 Promise 的执行,直到它得到解决。换句话说,它等待 Promise 解析,然后恢复异步函数。例如:

async function example(){
var data = await getData() // it waits until the promise is resolved
return data;
}

关于node.js - 回调函数与 Promise 和 Async wait 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56035233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com