首页 > 解决方案 > Callback 函数与 Promise 和 Async awit 的区别

问题描述

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

标签: node.jsnodejs-streamnodejs-server

解决方案


打回来

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

function(callback){

   //you do some tasks here that takes time

   callback();
}

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

承诺

承诺也像回调方法一样处理异步代码,但以更具可读性的方式。例如,而不是这个:

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 的执行,直到它被解决。换句话说,它等待承诺解决,然后恢复异步功能。例如:

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

推荐阅读