代码之家  ›  专栏  ›  技术社区  ›  Gourav Srivastava

我应该如何使用回调来获得期望的结果?

  •  0
  • Gourav Srivastava  · 技术社区  · 2 年前

    您好,我在使用promise时得到了期望的结果,但是当我从函数返回某些内容时,我应该如何通过回调实现它。

    
    
    const first = () => {
        return ("I am first");
    }
    
    const second = () => {
      return new Promise((resolve,reject) => {
          setTimeout(()=>{
            resolve("I am second");
          },1000);
      })
    }
    
    const third = () => {
        return("I am third");
    }
    
    //using promise
    
    const solve = async () => {
      var f = first();
      console.log(f);
      
      var ans = await second();
      console.log(ans);
      
      var t = third();
      console.log(t);
    }
    
    solve();
    

    const first = () => {
        return "I am first";
    }
    
    var temp;
    const second = (cb) => {
       setTimeout(function() {
        return "I am second";
        temp = cb();
       }, 1000);
    }
    
    const third = () => {
       return "I am third";
    }
    
    
    const solve = () => {
        var f  = first();
        console.log(f);
        
        var s = second(third);
        setTimeout(()=>{
          console.log(s);
          console.log(temp);
        },1100)
    }
    
    solve();
    

    输出应为

    我是第一个

    我是第三名

    1 回复  |  直到 2 年前
        1
  •  1
  •   Bergi    2 年前

    你不需要那种全球性的 temp 变量和 setTimeout second 真的不管用。应该是这样的 cb("I am second"); ,就像你通常打电话的地方一样 resolve("I am second"); 在一个 new Promise . 然后,您可以将该值作为要传递给的回调函数的参数接收 second(…)

    const first = () => {
        return "I am first";
    }
    
    const second = (cb) => {
        setTimeout(function() {
            cb("I am second");
        }, 1000);
    }
    
    const third = () => {
        return "I am third";
    }
    
    
    const solve = () => {
        var f  = first();
        console.log(f);
        
        second((s) => {
            console.log(s);
    
            const t = third();
            console.log(t);
        });
    }
    
    solve();

    注意,如果要使用,这与您的承诺版本没有什么不同 .then() 而不是 async await 语法:

    const solve = () => {
        var f = first();
        console.log(f);
      
        second().then((s) => {
            console.log(s);
      
            var t = third();
            console.log(t);
        });
    }