【发布时间】:2020-12-31 11:22:40
【问题描述】:
我试图了解这 3 个之间的区别。回调和承诺很清楚,但我不了解异步/等待的用法。我知道这是承诺的语法糖,但我尝试过的没有奏效。我正在分享我试图理解这一切的一段代码......
我尝试过使用数组
var array = [1,2,3];
和2个功能
-
get()在 1 秒内执行并控制台array -
post(item)在 2 秒内执行并在array中推送一个新项目
现在,我想要得到的是 post 方法应该首先执行 & get 在它之后,以便控制台上的结果应该是 [1,2,3,4] 而不是 [1,2,3]
回调
function get() {
setTimeout(() => console.log(array), 1000);
}
function post(item, callback) {
setTimeout(() => {
array.push(item);
callback();
}, 2000);
}
function init() {
post(4, get);
// returns [1,2,3,4] ✅
}
它工作正常,但如果回调太多,代码会更混乱......所以,
承诺
function get() {
setTimeout(() => console.log(array), 1000);
}
function post(item) {
return new Promise((resolve, reject) => setTimeout(() => {
array.push(item)
resolve();
}, 2000));
}
function init() {
post(4).then(get);
// returns [1,2,3,4] ✅
}
好的,代码更简洁。但仍然有多个then 呼叫...现在,
异步/等待
function get() {
setTimeout(() => console.log(array), 1000);
}
function post(item) {
setTimeout(() => {
array.push(item)
}, 2000);
}
async function init() {
await post(4);
get();
// returns [1,2,3] ❌
await post(4);
await get();
// returns [1,2,3] ❌
post(4);
await get();
// returns [1,2,3] ❌
}
更简洁的版本,但无论哪种方式,它都有效...我也尝试过这个(将两个函数(post 和get)转换为异步并使用then 调用)
async function get() {
setTimeout(() => console.log(array), 1000);
}
async function post(item) {
setTimeout(() => {
array.push(item)
}, 2000);
}
async function init() {
post(4).then(get);
// returns [1,2,3] ❌
}
但还是没用。所以我对这个功能(即异步/等待)完全感到困惑。请详细说明这个例子。在同样的情况下,请告诉我Promise.resolve 和Promise.all!谢谢
【问题讨论】:
-
在将
init从.then()语法更改为await糖时,您仍然需要使用返回承诺的post函数。
标签: javascript node.js promise async-await callback