如何在promise链中设置超时.then()

时间:2017-09-29 11:51:24

标签: javascript promise settimeout

我有一个按顺序执行的承诺链。但我想延迟其中一个,而不是让其他的执行,直到延迟的一个完成。我该如何做到这一点?我尝试了一个setTimeOut,但似乎承诺链是异步的,所以超时没有按预期工作。

var p = Promise.resolve("Hello");

p.then((result) => {
  console.log(result);
  console.log("========== Then Block 1");
  return "how are you";
}).then((result)=>{
  console.log(result);
  console.log("========== Then Block 2");
  return "I'm Fine! Thank you"
}).then((result) => {

  setTimeout(function(){
    console.log("Time out Done!");
  }, 3000);

  console.log(result);
  console.log("========== Then Block 3");
}).then(()=>{
  console.log("========== Then Block 4");
})

打印:

"Hello"
"========== Then Block 1"
"how are you"
"========== Then Block 2"
"I'm Fine! Thank you"
"========== Then Block 3"
"========== Then Block 4"
"Time out Done!"

我想要的是:

"Hello"
"========== Then Block 1"
"how are you"
"========== Then Block 2"
"I'm Fine! Thank you"
"Time out Done!"
"========== Then Block 3"
"========== Then Block 4"

1 个答案:

答案 0 :(得分:0)

创建一个新的承诺,并在setTimeout回调中解决它:

Promise
  .resolve("Hello")
  .then((result) => {
    console.log(result);
    console.log("========== Then Block 1");
    return "how are you";
  })
  .then(result => {
    console.log(result);
    console.log("========== Then Block 2");
    return "I'm Fine! Thank you";
  })
  .then(result => new Promise(resolve => { // <== create a promise here
    setTimeout(function() {
      console.log("Time out Done!");
      console.log(result);
      console.log("========== Then Block 3");
      resolve(); // <== resolve it in callback
    }, 3000);
  }))
  .then(() => {
    console.log("========== Then Block 4");
  });