无论使用Promise的时间如何,如何按顺序执行setTimeout?

时间:2017-03-31 14:26:00

标签: javascript

我目前正在使用这段代码:

var timeOne = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is one');
    }, Math.random() * 1000);
}); 

var timeTwo = new Promise(function(resolve,reject) {
    setTimeout(function(){
        console.log('This is two');
    }, Math.random() * 1000);
}); 

    timeOne.then(timeTwo);

我想要的是在timeTwo之前显示timeOne结果,无论Math.random()提供什么。我目前正在努力应对这个“不好”的承诺。任何人都可以澄清为什么上面的代码没有按预期工作? (它仍然可以在“这是一个”之前显示“这是两个”)。

2 个答案:

答案 0 :(得分:0)

var timeOne = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('This is one');
  }, Math.random() * 1000);
});

var timeTwo = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('This is two');
  }, Math.random() * 1000);
});

timeOne.then(function(m) {
  console.log(m);
  return timeTwo;
}).then(function(m) {
  console.log(m);
  return 'done';
}).then(function(m){
  console.log(m);
});

答案 1 :(得分:0)

基本上每个人都在评论中说。这是你如何做到的:

var timeOne = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(console.log('This is one'));
    }, Math.random() * 1000);
  }); 
}

var timeTwo = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve(console.log('This is two'));
    }, Math.random() * 1000);
  }); 
}

timeOne().then(timeTwo);