【发布时间】:2019-09-25 20:41:36
【问题描述】:
我了解回调函数,但我不了解promise方法和async和await。为什么在节点js中使用这三个函数。可以给出示例代码。
【问题讨论】:
-
要求查找教程的问题与 SO 无关。请阅读此on-topicHow to Ask
标签: node.js nodejs-stream nodejs-server
我了解回调函数,但我不了解promise方法和async和await。为什么在节点js中使用这三个函数。可以给出示例代码。
【问题讨论】:
标签: node.js nodejs-stream nodejs-server
回调是作为参数传递给另一个函数的函数,并在最后执行。像这样:
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;
}
【讨论】:
回调函数
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);
}
在此等待,直到文件变量得到它的值
【讨论】: