[英]return a value from a javascript callback
I need to pass a value to a function, which contains a modifier method, and then return
the modified value. 我需要将一个值传递给包含修改器方法的函数,然后
return
修改后的值。
What's the best way to do this? 最好的方法是什么?
I have a read
function (which parses content) and a scan
function (which looks for a word in the content. 我有一个
read
功能(用于解析内容)和一个scan
功能(用于在内容中查找单词)。
I have the following code so far: 到目前为止,我有以下代码:
scanContent = function(url){
read(url, function(err, article, meta) {
var content = article.title + article.content
return scan(content)
}
return scan(content)
});
return scan(content)
}
This obviously doesn't work, but I'm not really sure what the right approach is here. 这显然是行不通的,但是我不确定这是什么正确的方法。
You need to provide callback function parameter and call it with your result: 您需要提供回调函数参数,并将其与您的结果一起调用:
function byThree(n, callback) {
var x = n * 3;
callback(x);
}
var multiply = function(n, callback) {
byThree(n, function(result) {
callback(result);
});
};
multiply(5, function(result) {
console.log('result: ' + result);
});
function byThree(n){
return n * 3;
}
multiply = function(n){
return byThree(n);
};
console.log("result: "+multiply(5));
Though the following makes more sense: 尽管以下更有意义:
function multiply(n, m){
return n * m;
};
console.log("result: "+multiply(5, 3));
And the following makes even more sense: 以下内容更有意义:
console.log("result: " + 5 * 3);
If function gets a meaningful result from an inner callback, then it can return a meaningful result only by another callback. 如果函数从内部回调获得有意义的结果,则它只能通过另一个回调返回有意义的结果。 You can't trick the program flow.
您不能欺骗程序流程。
So, it would be like that: 因此,就像这样:
var scanContent = function(url, cb){
read(url, function(err, article, meta) {
var content = article.title + article.content
return cb(scan(content)); // asume 'scan' is defined elsewhere
}
});
};
scanContent(function(text) { console.log(text); });
This could lead to the callback hell . 这可能会导致回调地狱 。 There is Promise from ES6 to avoid that.
ES6 承诺避免这种情况。 And generators to make the code even more straightforward.
和生成器使代码更加直接。
With Promises (and arrow functions): 具有承诺(和箭头功能):
var scanContent = function(url){
// simplified; it's better to always return a promise in the real code
return read(url).then((err, article) => scan(article.title + article.content));
};
scanContent('example.com').then((text) => console.log(text));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.