推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Plumes

请问 JavaScript 中有没有不需要注入的回调实现方法?

  •  
  •   Plumes · Aug 12, 2017 · 2609 views
    This topic created in 3259 days ago, the information mentioned may be changed or developed.

    遇到的问题是这样的,有一个函数 func_a :

    function func_a() {
      if(something){
        func_b();
      } else {
        func_c();
      }
    }
    

    func_a 里面可能执行 func_b , 也可能执行 func_c, 而 func_bfunc_c 在执行结束后还需要执行一些共同的操作,这里就需要对两个函数进行回调 现在能实现需求的方法就是

    function func_b(callback) {
      //do something
     callback();
    }
    
    function func_a() {
      if(something){
        func_b(func_d);
      } else {
        func_c(func_d);
      }
    }
    

    这样的话需要在 func_a 中调用的函数,都需要接受 callback 参数,最后再去调用 callback(),而实际问题中,func_b 这些函数是在外部实现,然后作为参数传入 func_a 的,所以每定义一个都需要加上这两行, 感觉有些冗余。

    func_b 这类函数既可能执行的是 console.log() 这些同步操作,也可能执行的是 fetch(api).then().catch() 这样的异步操作。

    不知道有没有什么方法使 func_b 不需要接受外部参数,完全在 func_a 内部实现回调,保证在 func_b 执行完成之后去执行某些操作。

    Supplement 1  ·  Aug 12, 2017

    再具体一下

    function func_b() {
      setTimeout(()=>{console.log("first")}, 1000);
    }
    
    function func_a() {
     //console.log("second")
    }
    

    有没有什么办法在完全不动 func_b 的情况下,使控制台依次输出 "first", "second"

    8 replies    2017-08-12 16:14:46 +08:00
    Pastsong
        1
    Pastsong  
       Aug 12, 2017
    Promise.all
    binux
        2
    binux  
       Aug 12, 2017
    Promise.resolve
    Chingim
        3
    Chingim  
       Aug 12, 2017
    不考虑 async/await 吗?
    Plumes
        4
    Plumes  
    OP
       Aug 12, 2017
    @Pastsong @binux

    问题已更新,继续请教
    ```
    Promise.resolve(fun_b()).then(()=>{console.log("second")})
    ```
    输出的还是 second、first
    ETiV
        5
    ETiV  
       Aug 12, 2017 via iPhone
    不改造 b、c 没办法
    无论是啥 promise async 都得按照它的规范来写

    如果本来有回调的写法,bluebird 库貌似可以 promisify 它 http://bluebirdjs.com/docs/api/promise.promisify.html

    但本来没回调的,不改不行了
    yanqing07
        6
    yanqing07  
       Aug 12, 2017
    fun_b 要改成 Promise 形式啊
    binux
        7
    binux  
       Aug 12, 2017 via Android
    没有可能在 func_b 本身不支持的情况下支持回调
    will0404
        8
    will0404  
       Aug 12, 2017
    直说吧。不可能。
    你必须得知道 func_b 什么时候执行结束,否则没有顺序可言。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1354 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 17:07 · PVG 01:07 · LAX 10:07 · JFK 13:07
    ♥ Do have faith in what you're doing.