【问题标题】:JavaScript problem with promise chaining example承诺链示例的 JavaScript 问题
【发布时间】:2019-02-02 06:28:51
【问题描述】:

我很难理解 javaScript 中的链式 Promise,所以我决定做一个例子并练习一些代码,这就是我想做的......

  • 做一个“繁重的任务”5秒
  • 在繁重的任务完成后执行“中等任务”3 秒 成功
  • 如果“中等任务”成功到 2 秒的“小”任务
  • “小任务”必须显示繁重任务的成功信息
  • 如果“中等任务”失败,则执行 1 秒的“错误任务”说明 失败原因
  • 在所有这些都在进行的同时执行“其他一些任务......”

var p = new Promise(function(resolve, request) {

  setTimeout(function() {
   console.log("Inside heavy task...");
   resolve("Heavy task was a success");
  }, 5000);
 })


 .then(function(value) {

  setTimeout(function(value) {
   console.log("Inside medium task...");
   resolve(value);
   //reject("Medium task failed !");
  }, 3000);
 })

 .then(function(value) {

  console.log("Inside small task...");
  console.log("From small task : " + value);
 })

 .catch( function(reson){
  
  setTimeout(function(reason){
  console.log("Inside error task...");
  console.log("Failed due to "+reason);
  },1000);
 });

console.log("Some other tasks...");

我知道我的代码是错误的,有人可以纠正这个问题并解释应该如何做。

【问题讨论】:

    标签: ecmascript-6 es6-promise


    【解决方案1】:

    首先,如果你想给setTimeout的回调函数传递额外的参数,那么它是这样完成的

    setTimeout(callback, time, param1, param2, ...)
    

    现在在您的代码 sn-p 中,将第二个 setTimeout 函数包装在一个 Promise 中并返回该 Promise。此外,如果您希望小任务是异步的,那么也将其包装在一个 Promise 中并返回该 Promise。

    var p = new Promise(function(resolve, reject) {
      setTimeout(function() {
       console.log("Inside heavy task...");
       resolve("Heavy task was a success");
      }, 5000);
    })
      .then(function(value) {
        var p2 = new Promise(function(resolve, reject) {
          setTimeout(function() {
            console.log("Inside medium task...");
            resolve(value);
            // reject("Medium task failed !");
          }, 3000);
        });
        return p2;
      })
      .then(function(value) {
        console.log("Inside small task...");
        console.log("From small task : " + value);
      })
      .catch(function(reason) {
        setTimeout(function(){
          console.log("Inside error task...");
          console.log("Failed due to "+ reason);
        }, 1000);
      });
    
    console.log("Some other tasks...");
    

    我希望这会有所帮助:)

    【讨论】:

    • 谢谢,Kartik 这正是我正在寻找的答案。当您说“另外,如果您希望小任务是异步的,那么将其包装在一个承诺中并返回该承诺。”只有一个问题,我是一个新手,您能解释一下“小任务是异步的”是什么意思.这是否意味着它将与正在执行的任何其他任务一起执行,例如“console.log(“Some other tasks...”);"在示例中?
    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2016-04-14
    • 2019-08-29
    相关资源
    最近更新 更多