promise - Javascript Promise resolve 方法在控制台中打印。如何?
问题描述
请看下面的 javascript 代码。当我在浏览器控制台窗口中运行此代码时,会收到下面提到的输出。我是 javascript 和承诺的新手。请帮助我了解如何在浏览器控制台中打印“已解决”?
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
浏览器控制台中的输出:
打电话
解决
现在我的问题是为什么“已解决”会打印在控制台中?据我所知, then() 方法应该在调用 resolve() 方法时执行。
解决方案
await
运算符用于等待Promise
结算。Promise
如果它不是 a ,它会返回 the 或值本身的已实现值Promise
。
在您的代码中,由于resolveAfter2Seconds()
函数返回 a Promise
,因此在以下语句中
const result = await resolveAfter2Seconds();
javascript 等待Promise
解决,然后将其履行值,即分配给'resolved'
常数result
。之后,您在控制台上登录,result
这就是在控制台上'resolved'
登录的原因。
函数中每个语句上方的注释asyncCall
将帮助您理解输出。
async function asyncCall() {
// log 'calling' on the console
console.log('calling');
// wait for the promise to resolve and then
// assign the fulfillment value to 'result'
const result = await resolveAfter2Seconds();
// log the value with which promise returned
// by 'resolveAfter2Seconds' function resolved
console.log(result);
}
据我所知, then() 方法应该在调用 resolve() 方法时执行。
我看不到您.then()
在代码中调用方法的位置。.then()
如果您在 any 上注册任何回调调用.then()
方法,则会调用方法Promise
。
除了使用async-await
语法,您可以更改代码,如下所示,以查看注册的回调.then()
在 2 秒后被调用。
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
// store the promise returned by 'resolveAfter2Seconds' function
const p = resolveAfter2Seconds();
// register a callback function to be invoked after 2
// seconds with the resolved value
p.then(resolvedValue => {
console.log('callback invoked');
console.log('Promise resolved with the value of: ' + resolvedValue);
}).catch(error => console.log(error));
从您的问题中可以清楚地看出您对代码的输出感到困惑,因为它使用async-await
语法而不是promise-chaining
. async-await
是使用.then()
方法调用的常规承诺代码的语法糖。
我建议您访问以下链接以了解async-await
语法的工作原理。一旦你理解了这一点,你将能够理解输出。
推荐阅读
- html - 防止html子元素继承父宽度
- java - Java中带接口的微分函数
- javascript - 如果里面没有评论,请删除帖子
- jmeter - HTTP 响应和连接超时
- javascript - Mongoose:如何使用两个字段对聚合响应进行排序
- virtual-machine - 如何创建和共享用于开发的 VM 环境
- java - 将 WebView 实现为片段的问题
- c++ - 有没有一种安全的方法可以在没有 sudo 权限的情况下从 C++ 关闭 Jetson Nano (Linux)?
- javascript - Javascript 刷新/重新初始化 DOM
- firebase - 无法解决:com.google.firebase:firebase-core-ktx: