如何在不影响外部功能的情况下使此代码顺序化

时间:2019-06-06 05:13:16

标签: javascript async-await

我需要这样的顺序:

潜伏在阴影中; 结束

如何在不触摸“顺序”功能的情况下实现这种效果?

实现顺序运行

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 :(得分:-1)

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();

您可以这样做!