简体   繁体   English

设置回调函数以在javascript中返回值

[英]set callback function to return value in javascript

Here is my code: 这是我的代码:

function render(){
    var el;
    setTimeout(function(){
      func();
    },1000);
    return el;
  }

function func(){
    //do something here;
}

setTimeout is async, so el will be returned before execute func.I want to return el after calling func, how should I write the callback function? setTimeout是异步的,所以el将在执行func之前返回。我想在调用func之后返回el,如何编写回调函数?

use a callback - a function that el will be passed to: 使用回调el将传递给的函数:

function render(callback){
    var el;
    setTimeout(function(){
      func();
      callback(el);
    },1000);
  }

function func(){
    //do something here;
}

function elReady(el){
    // use `el`
}

So now you can use render(elReady) . 因此,现在您可以使用render(elReady)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM