Promis的更简单舒服的使用方式 ,配合Async/await 使用

Async/await

   There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use.

Async functions

  Let’s start with the async keyword. It can be placed before a function, like this:

1
2
3
async function f() {
  return 1;
}  

  The word “async” before a function means one simple thing: a function always returns a promise.

  Other values are wrapped in a resolved promise automatically.

  For instance, this function returns a resolved promise with the result of 1; let’s test it:

1
2
3
4
5
async function f() {
  return 1;
}
 
f().then(alert); // 1
…We could explicitly return a promise, which would be the same: 
1
2
3
4
5
async function f() {
  return Promise.resolve(1);
}
 
f().then(alert); // 1

  

  So, async ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right?

  But not only that. There’s another keyword, await, that works only inside async functions, and it’s pretty cool.

Await

  The syntax:

1
2
// works only inside async functions
let value = await promise; 

  The keyword await makes JavaScript wait until that promise settles and returns its result.

  Here’s an example with a promise that resolves in 1 second:

1
2
3
4
5
6
7
8
9
10
11
12
async function f() {
 
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });
 
  let result = await promise; // wait until the promise resolves (*)
 
  alert(result); // "done!"
}
 
f();

  

  The function execution “pauses” at the line (*) and resumes when the promise settles, with result becoming its result.

  So the code above shows “done!” in one second.

  Let’s emphasize: await literally makes JavaScript wait until the promise settles, and then go on with the result.

  That doesn’t cost any CPU resources, because the engine can do other jobs in the meantime: execute other scripts, handle events, etc.

  It’s just a more elegant syntax of getting the promise result than promise.then, easier to read and write.

 

   Reference(查看更多介绍请点击下方链接) :

  https://javascript.info/async-await

posted on   滚动的蛋  阅读(312)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示