zoukankan      html  css  js  c++  java
  • 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:

    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:

    async function f() {
      return 1;
    }
    
    f().then(alert); // 1
    …We could explicitly return a promise, which would be the same: 
    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:

    // 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:

    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

  • 相关阅读:
    #include "stdafx.h" 错误?
    扩频技术
    求数组中只出现一次的数字(算法)
    1.3一摞烙饼的排序
    嵌套类
    企业级邮件服务软件推荐
    关于Linq To Sql中Detach方法和一个公共基类
    asp.net(c#) 将dbf转换为xls或wps,并将数据的列名改成中文;并判断本机是否安装office2003,2007和wps2007,2010
    一句代码解决IE8兼容问题(兼容性视图)
    asp.net(C#)套用模板操作Excel
  • 原文地址:https://www.cnblogs.com/irobotzz/p/12448832.html
Copyright © 2011-2022 走看看