简体   繁体   English

javascript:在回调函数中传递返回值

[英]javascript: pass return value in callback function

Please help me understand this: 请帮助我理解这一点:

I have an object self.domainSettings() which has a save method. 我有一个对象self.domainSettings() ,它具有save方法。 The save returns the result which I want to use in callback function to populate success or error message. save返回要在回调函数中使用的结果,以填充成功或错误消息。 I am using following code: 我正在使用以下代码:

self.domainSettings().save(function(data){
    console.log('in here');
    console.log(data);
    console.log('outta here');
 }());

function save(){
  return 'success';
};

When I do console.log(data) is it guaranteed that the save has finished executing ? 当我执行console.log(data)是否可以确保保存已完成执行? Also it says data is undefined because the return value of save is not getting passed to callback function I guess. 它还说数据是不确定的,因为我猜想保存的返回值没有传递给回调函数。 How do I get that ? 我怎么得到的?

You have to pass callback in save() in order to access the result from a callback. 您必须在save()中传递回调才能从回调中访问结果。

function save(fn){
  return fn('success');
};

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

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