javascript - Return Promise 和 await 完全一样吗?
问题描述
考虑以下 2 个函数:一个返回 promise 对象,一个使用 await。它们在幕后的行为是否完全相同?
async function f1 (event) {
const promise = new Promise(function(resolve, reject) {
fetch('https://google.com')
.then(p=>p.status)
});
return promise
}
async function f2 (event) {
const res = await fetch('https://google.com');
return res.status;
}
我相信我也可以这样称呼:
var r1 = await f1(url);
var r2 = await f2(url);
这里的问题:1. 2 个调用是否正确?2. f1 和 f2 在钩子下,它们的行为和用法完全相同吗?
解决方案
如果http.get
返回一个 Promise,您可以简化 Promise 示例以使其看起来像await
示例。为了简单地回答你的问题,他们用不同的语法做同样的事情。
async function f1 (event) {
return https
.get(url)
.then(res => res.statusCode);
}
async function f2 (event) {
const res = await https.get(url);
return res.statusCode;
}