【问题标题】:difference between Callback function and Promise and Async awitCallback 函数与 Promise 和 Async await 的区别
【发布时间】:2019-09-25 20:41:36
【问题描述】:

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

【问题讨论】:

标签: node.js nodejs-stream nodejs-server


【解决方案1】:

回调

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

function(callback){

   //you do some tasks here that takes time

   callback();
}

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

承诺

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

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

【讨论】:

    【解决方案2】:

    回调函数

    var fs = require('fs');
    
    fs.readFile(fileName, 'utf8', function read(err, contents) {
       console.log(contents);
    });
    
    console.log('after calling readFile');
    

    这里的函数 read(err, contents){} 是一个回调函数,在完成读取文件时打印内容。 但在某些情况下,问题可能是“在调用 readFile 之后”在读取文件之前显示到控制台。 由于Node Js以异步方式执行语句。

    承诺

    var fs = require('fs');
    function readMyFile(fileName)
    {
       return new Promise(function(resolve,reject)
       {
          fs.readFile(fileName, 'utf8', function read(err, contents) {
          if(err)
                reject(err)
          else
                resolve(contents)
       });
       }
    }
    
    var file = readMyFile(fileName).then(result=>{console.log(result);console.log('after calling readFile');  }).catch(err=>{console.log("Error Occurred",err)});
    console.log(file);
    

    这里的函数 readMyFile(fileName) 是一个返回 promise 的函数,打印 then 块中的内容并在 catch 块中显示错误。 但是这里 console.log(file); 行无需等待 file 变量 被定义

    就被执行

    异步/等待

    var fs = require('fs');
    function readMyFile(fileName)
    {
       return new Promise(function(resolve,reject)
       {
          fs.readFile(fileName, 'utf8', function read(err, contents) {
          if(err)
                reject(err)
          else
                resolve(contents)
       });
       }
    }
    
    async function read()
    {
       var file = await readMyFile(fileName);
       console.log(file);
    }
    

    在此等待,直到文件变量得到它的值

    • await 仅适用于承诺
    • await 只能在异步函数中使用

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 2020-09-22
      • 2019-04-17
      • 1970-01-01
      • 2021-09-20
      • 2013-09-04
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      相关资源
      最近更新 更多