发布于2026-07-21 阅读(0)
扫一扫,手机访问
在Ubuntu上搞Ja vaScript异步编程,其实路子挺多的。无非就是回调函数、Promises、async/await这几把刷子。下面逐个拆解,看看它们各自怎么玩。

回调函数这套路,算是异步编程的老祖宗了。简单来说,就是把一个函数塞进另一个函数里当参数,等异步操作搞完了,再回头调用它。
function asyncOperation(callback) {
setTimeout(() => {
const result = 'Operation completed';
callback(result);
}, 1000);
}
asyncOperation((result) => {
console.log(result); // 输出: Operation completed
});
看起来挺直观,但要是嵌套多了,容易掉进“回调地狱”——一坨花括号层层叠叠,代码读起来像翻山越岭。
ES6带着Promise来了,可以说是给回调吃了颗定心丸。它用链式调用代替了嵌套,代码瞬间清爽不少。
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = 'Operation completed';
resolve(result);
}, 1000);
});
}
asyncOperation()
.then((result) => {
console.log(result); // 输出: Operation completed
})
.catch((error) => {
console.error(error);
});
这里的关键是:Promise对象代表一个未来的值,要么成功(resolve),要么失败(reject)。然后通过.then和.catch来分别处理,逻辑清晰,一目了然。
到了ES2017,async/await横空出世。它本质上就是Promise的语法糖,但写起来跟同步代码一样,可读性直接拉满。
async function run() {
try {
const result = await asyncOperation();
console.log(result); // 输出: Operation completed
} catch (error) {
console.error(error);
}
}
run();
注意,async函数内部可以用await等待一个Promise,而try/catch则负责捕获异常。对于那些习惯写同步代码的同学来说,这简直就是救星。
光说不练假把式,下面整一个完整的示例,跑在Ubuntu的Node.js环境里,看看三种方式一起上阵的效果。
先确保机器上装了Node.js。如果还没装,终端里敲这几行就行:
sudo apt update
sudo apt install nodejs
sudo apt install npm
新建一个文件,比如async_example.js,把下面的代码贴进去:
// 使用回调函数
function asyncOperationWithCallback(callback) {
setTimeout(() => {
const result = 'Operation completed with callback';
callback(result);
}, 1000);
}
asyncOperationWithCallback((result) => {
console.log(result); // 输出: Operation completed with callback
});
// 使用Promises
function asyncOperationWithPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = 'Operation completed with promise';
resolve(result);
}, 1000);
});
}
asyncOperationWithPromise()
.then((result) => {
console.log(result); // 输出: Operation completed with promise
})
.catch((error) => {
console.error(error);
});
// 使用async/await
async function run() {
try {
const result = await asyncOperationWithPromise();
console.log(result); // 输出: Operation completed with promise
} catch (error) {
console.error(error);
}
}
run();
在终端里执行:
node async_example.js
你会看到这样的输出:
Operation completed with callback
Operation completed with promise
Operation completed with promise
可以看到,三种方式都达到了同样的效果——延迟一秒后输出结果。选择哪种,全看你的项目风格和个人习惯。回调函数适合简单场景,Promise能优雅地处理链式依赖,而async/await则让代码更像同步逻辑,读起来心情舒畅。在Ubuntu环境下,这些方法都能无缝运行,随便挑一个上手就行。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8