代码之家  ›  专栏  ›  技术社区  ›  user1037355

javascript async await适合web应用程序吗

  •  0
  • user1037355  · 技术社区  · 9 年前

    在阅读一些使用新javascript语法的异步/等待示例时,我发现了以下代码示例:

    const axios = require('axios'); // promised based requests - like fetch()
    
    function getCoffee() {
      return new Promise(resolve => {
        setTimeout(() => resolve('☕'), 2000); // it takes 2 seconds to make coffee
      });
    }
    
    async function go() {
      try {
        // but first, coffee
        const coffee = await getCoffee();
        console.log(coffee); // ☕
        // then we grab some data over an Ajax request
        const wes = await axios('https://api.github.com/users/wesbos');
        console.log(wes.data); // mediocre code
        // many requests should be concurrent - don't slow things down!
        // fire off three requests and save their promises
        const wordPromise = axios('http://www.setgetgo.com/randomword/get.php');
        const userPromise = axios('https://randomuser.me/api/');
        const namePromise = axios('https://uinames.com/api/');
        // await all three promises to come back and destructure the result into their own variables
        const [word, user, name] = await Promise.all([wordPromise, userPromise, namePromise]);
        console.log(word.data, user.data, name.data); // cool, {...}, {....}
      } catch (e) {
        console.error(e); // 💩
      }
    }
    
    go();
    

    我刚刚被投入到一个使用AWS DynomoDB的项目中,其所有操作的抽象类都在async/await后面。。。如果这是阻塞,这肯定会破坏性能?

    1 回复  |  直到 7 年前
        1
  •  2
  •   GolezTrol    9 年前

    等候 做 块

    await 确实使 你的 代码等待。 当你还在等待的时候,没有魔法可以让等待之后的代码运行。在本例中,在咖啡喝完之前,不会触发这些ajax请求。

    但是,您可以等待多个异步进程。您在某个时候发布的示例同时触发了三个Ajax请求,并仅在它们全部触发后才等待它们。这些请求将并行执行。

    ..你只需要在需要答案的时候等待

    关键是,你异步启动一些东西,最终会结束(承诺!)。您可以在真正需要等待该调用的结果时(最好仅在该情况下)调用wait。因此,如果您使用await调用每个异步方法,那么效果就消失了,但是如果您调用它们,将承诺存储在变量中,然后在最后等待它们,那么您将并行运行长操作。这个例子展示了“坏”的用法(喝咖啡,直到完成才开始工作),然后是好的用法(同时做三个请求)。

    您可以通过只等待咖啡和最后的第一个请求来“优化”示例,就像它等待其他请求一样,因此它并行执行5件事情,而不是3件。只有当您不需要下一个异步函数中第一个异步函数的结果时,这才有效。

    我之前说过,立即调用单个同步函数是不好的。情况并非总是如此,因为您只能使用 等候 在一个本身是异步的函数中,函数的调用方不会被阻止(除非它也调用wait)。

    例如,您可以创建一个简单的函数来获取一些数据,该函数使用 await AjaxShizzleGoesHere() 等候 ,并且被阻止),但函数的调用方不必立即等待结果,它可以先启动其他异步函数。