在 JavaScript 中使用 `then()` 和 Async/Await
发出异步请求时,你可以使用 async /awaitthen()
或async/await。 async/await 和async/ then()
await 非常相似。
区别在于,在async 函数中,JavaScript 会暂停函数执行,直到 Promise 条件成立。使用 async 时then()
,函数的其余部分将继续执行,但 JavaScript 不会执行.then()
回调,直到 Promise 条件成立。
async function test() {
console.log('Ready');
let example = await fetch('http://httpbin.org/get');
console.log('I will print second');
}
test();
console.log('I will print first');
如果您使用 Promise 链then()
,则需要将要在请求之后执行的任何逻辑放入Promise 链中。放入请求链中的任何代码都会在请求完成之前fetch()
立即执行。fetch()
function test() {
console.log('Ready');
let example = fetch('http://httpbin.org/get').then((res) => {
console.log('This is inside the then() block');
});
console.log('This is after the fetch statement where we are now executing other code that is not async');
}
test();
console.log('this is after the entire function');
我们建议尽可能使用 async/await,并尽量减少 Promise 链式调用。Async/await 让 JavaScript 代码更容易被不太熟悉 JavaScript 的开发者理解,也更易于阅读。
文章来源:https://dev.to/masteringjs/using-then-vs-async-await-in-javascript-2pma