Как сделать этот код последовательным, не касаясь внешней функции - PullRequest
0 голосов
/ 06 июня 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 }`);
}

function sequential(){
    msg();
    console.log('the end');
}

sequential();

Мне нужна такая последовательность:

?lurks in the shadows
the end

Как добиться такого результата, не касаясь «последовательной» функции?

Текущий результат:

the end
?lurks in the shadows

1 Ответ

0 голосов
/ 06 июня 2019

function who(data) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(data + '?');
    }, 200);
  });
}

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

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

function msg() {
  return who('')
  .then(what)
  .then(where);
}

function sequential(){
    return msg()
    .then((respo) => {
      console.log(JSON.stringify(respo));
      console.log('the end');
    });
    
}

sequential();

Вы можете сделать это!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...