javascript 简单的异步/等待示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 简单的异步/等待示例相关的知识,希望对你有一定的参考价值。

//  Node 7.6 has async/await! Here is a quick run down on how async/await works

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();

以上是关于javascript 简单的异步/等待示例的主要内容,如果未能解决你的问题,请参考以下文章

javascript 简单的异步/等待示例

javascript 简单的异步/等待示例

javascript 简单的异步 - 等待

javascript 简单的异步反应路由器v4示例

龙卷风 python 的简单异步示例

ajax的简单使用