📜  变量中的异步函数 - 无论代码示例

📅  最后修改于: 2022-03-11 14:56:12.889000             🧑  作者: Mango

代码示例1
function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
};

(async function(x) { // fonction asynchrone immédiatement appelée
  var a = resolveAfter2Seconds(20);
  var b = resolveAfter2Seconds(30);
  return x + await a + await b;
})(10).then(v => {
  console.log(v);  // affiche 60 après 2 secondes.
});

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

add(10).then(v => {
  console.log(v);  // affiche 60 après 4 secondes.
});