【js】async和await运用

摘自http://es6.ruanyifeng.com/#docs/async#co模块

关于asyncawait运用

个人明白:在每个函数前面的都加上async,函数内部,假如是异步操纵,直接在其前面加上await即可,守候一步函数实行的效果。await背面能够接任何变量,能够是常量或许promiseasync润饰的函数自动变成一个promise.一般情况下,await敕令背面是一个 Promise 对象。假如不是,会被转成一个马上resolve的 Promise 对象。

//经由async润饰以后,自动变成promise对象
async function f() {
  return 'hello world';
}

f().then(v => console.log(v))
// "hello world"

async function f() {
  return await 123;
}

f().then(v => console.log(v))
// 123
//毛病处置惩罚 
async function f() {
  throw new Error('出错了');
}

f().then(
  v => console.log(v),
  e => console.log(e)
)
// Error: 出错了

async中毛病处置惩罚

//运用catch捕获毛病
async function f() {
  await Promise.reject('出错了');
}

f()
.then(v => console.log(v))
.catch(e => console.log(e))
// 出错了
async function main() {
  try {
    var val1 = await firstStep();
    var val2 = await secondStep(val1);
    var val3 = await thirdStep(val1, val2);

    console.log('Final: ', val3);
  }
  catch (err) {
    console.error(err);
  }
}
//运用async掌握指定时候打印
function timeout(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function asyncPrint(value, ms) {
  await timeout(ms);
  console.log(value)
}

asyncPrint('hello world', 50);

多种形式

const foo = async function(){}
async function foo(){}
const foo = async () => {};

并发处置惩罚

let foo = await getFoo();
let bar = await getBar();
//======================
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
//运用下面的体式格局是,使一步操纵同时触发。最上面的体式格局是同步实行。


//并发实行的体式格局挑选
async function dbFuc(db) {
  let docs = [{}, {}, {}];
  let promises = docs.map((doc) => db.post(doc));

  let results = await Promise.all(promises);
  console.log(results);
}

// 或许运用下面的写法
//运用for轮回掌握了运用await的时候
async function dbFuc(db) {
  let docs = [{}, {}, {}];
  let promises = docs.map((doc) => db.post(doc));

  let results = [];
  for (let promise of promises) {
    results.push(await promise);
  }
  console.log(results);
}
    原文作者:pengj
    原文地址: https://segmentfault.com/a/1190000008011822
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞