如何在javascript中使用aync / await?

时间:2017-05-17 16:08:50

标签: javascript async-await

如何在 javascript 中使用async/await

我该怎么做?

是否有任何帮助?

1 个答案:

答案 0 :(得分:3)

  

async / await 函数的目的是简化行为   同步使用promises并在a上执行某些行为   承诺小组。就像Promises类似于结构化   回调, async / await 类似于组合生成器和   的承诺。

见这个例子:

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function add1(x) {
  var a = resolveAfter2Seconds(20);
  var b = resolveAfter2Seconds(30);
  return x + await a + await b;
}

add1(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

async function add2(x) {
  var a = await resolveAfter2Seconds(20);
  var b = await resolveAfter2Seconds(30);
  return x + a + b;
}

add2(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

返回Promise的API将产生一个promise链,并将该函数拆分为多个部分。请考虑以下代码:

function getProcessedData(url) {
  return downloadData(url) // returns a promise
    .catch(e => {
      return downloadFallbackData(url); // returns a promise
    })
    .then(v => {
      return processDataInWorker(v); // returns a promise
    });
}

可以使用单个异步函数重写它,如下所示:

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url); 
  } catch(e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}