Как я могу использовать async / await в JavaScript? - PullRequest
0 голосов
/ 21 ноября 2019

У меня есть следующий код:

function one() {

    setTimeout(() => {

        console.log('one');
    }, 2000);
}

function two() {
    console.log('two');
}

function three() {
    console.log('three');
}

function wrapper() {
    one();
    two();
    three();
}

wrapper();

Это, конечно, консоль регистрирует их в следующем порядке: два три один

Используя async / await, я бы хотел консоль войти ихв следующем порядке: один два три

Я не уверен, как этого добиться.

Спасибо

Ответы [ 2 ]

1 голос
/ 21 ноября 2019

async function one(){ 
  await new Promise(resolve => 
  setTimeout(async () => {
     await resolve(console.log('one'));
    }, 2000));
 
}

function two() {
    console.log('two');
}

function three() {
    console.log('three');
}
async function wrapper(){ await one(); two(); three();}

wrapper();
0 голосов
/ 21 ноября 2019
function who() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('?');
    }, 200);
  });
}

function what() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('lurks');
    }, 300);
  });
}

function where() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('in the shadows');
    }, 500);
  });
}

async function msg() {
  const a = await who();
  const b = await what();
  const c = await where();

  console.log(`${ a } ${ b } ${ c }`);
}

msg(); // ? lurks in the shadows <-- after 1 second
...