Quite literally, callbacks can be understood as calling something back. In programming, we use a call to imply that we're calling a function, so what's callback? To put simply, it's one function calling another. Quite literally, callbacks can be understood as calling something back. In programming, we use a call to imply that we're calling a function, so what's callback? To put simply, it's one function calling another.
从字面上看, 回调可以理解为回调某些东西。 在编程中,我们使用一个调用来暗示我们正在调用一个函数,那么回调是什么呢? 简而言之,它是一个函数调用另一个函数。 从字面上看,回调可以理解为回调某些东西。 在编程中,我们使用一个调用来暗示我们正在调用一个函数,那么回调是什么呢? 简而言之, 它是一个调用另一个函数的函数 。
Now let's see the more accurate definition of a callback with an example.
现在,让我们看一个示例的更准确的回调定义。
A callback is a function that is passed to another function as a parameter and then invoked by other functions. The function to which the callback is passed is often referred to as a higher-order function. Conversely, Higher-Order Functions operate on other functions by either taking them as arguments or by returning them.
回调是一个函数,将其作为参数传递给另一个函数,然后由其他函数调用 。 回调传递给的函数通常称为高阶函数。 相反,高阶函数通过将其他函数作为参数或通过将其返回来对其他函数进行操作。
function higherOrder(callbackfn) {
console.log('invoked higher order! ');
callbackfn();
}
function callbackfn() {
console.log('invoked callback! ');
}
higherOrder(callbackfn);
Output
输出量
invoked higher order!
invoked callback!
The above example shows the simplest version of callbacks. The names of the functions are self-explanatory and you can understand how they are working. Now that we have a basic knowledge of what callbacks are, we can move to understand asynchronous functions with callbacks.
上面的示例显示了最简单的回调版本。 函数的名称不言自明,您可以了解它们的工作方式。 既然我们对什么是回调有了基本的了解,我们就可以开始理解带有回调的异步函数。
Recall that asynchronous functions are those which execute after a certain time interval. They are not immediately executed and while they are running in the background we can have some other code running synchronously. For example, a spinner or a loader you see on a website that runs while they are fetching data through asynchronous calls.
回想一下异步函数是在一定时间间隔后执行的函数。 它们不会立即执行,并且当它们在后台运行时,我们可以使其他一些代码同步运行。 例如,您在网站上看到的微调器或装载程序在它们通过异步调用获取数据时运行。
Example:
例:
var timerID = setTimeout(function() {
console.log('Runs in 3s');
}, 3000);
setTimeout(function() {
console.log('cancelling first timeout', timerID);
const a = 10;
clearTimeout(timerID);
return a;
}, 2000);
Output
输出量
cancelling first timeout 175
Let's understand what's going on in the above code. We are running the first asynchronous function in seconds but before that happens we cancel that function in two seconds. Makes sense, but why didn't we get the value 10 returned from our second asynchronous function? We know it executed since this was the function that canceled our first asynchronous function, so we know it did run right from it's the first line to the last line, so why didn't we get 10 on the console?
让我们了解以上代码中发生了什么。 我们在几秒钟内运行第一个异步函数,但是在此之前,我们在两秒钟内取消了该函数。 是有道理的,但是为什么我们没有从第二个异步函数返回值10? 我们知道它已执行,因为这是取消我们第一个异步函数的函数,所以我们知道它确实是从第一行到最后一行运行的,所以为什么在控制台上没有得到10?
function run() {
const a = 10;
return a;
}
run();
Output
输出量
10
The above code shows a normal function which returns some value. When we try to return the same value from an asynchronous callback function, we simply get nothing. So how do we do that?
上面的代码显示了一个正常的函数,该函数返回一些值。 当我们尝试从异步回调函数返回相同的值时,我们什么也得不到 。 那么我们该怎么做呢?
A promise is simply an object that represents a task that will be completed in the future.
许诺只是代表将来要完成的任务的对象。
A promise is a way of returning values from asynchronous callback functions. To understand promise in simpler terms you can imagine it as a token being given in a government office to get some help on a certain problem. That token represents that you will be called in at some later time and your problem will be addressed. That token, analogically, is a promise. The help you get from the office is the invocation of your callback.
promise是从异步回调函数返回值的一种方法。 要简单地理解诺言,您可以将其想象为政府机构提供的代币,以就某些问题寻求帮助。 该令牌表示您将在以后的某个时间与您联系,并且您的问题将得到解决。 类似地,该令牌是一个承诺。 从办公室获得的帮助是调用回调。
var p = new Promise(function(resolve, reject) {
resolve(10);
});
undefined
p.then(function(a) {
console.log('Promise p resolved with data: ', a);
})
Output
输出量
VM2636:2 Promise p resolved with data: 10
Promise {: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
We returned value from an asynchronous callback function using a promise!
我们使用promise从异步回调函数返回了值!
Let's see another example:
让我们看另一个例子:
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
var randomNo = Math.floor(Math.random() * 10);
resolve(randomNo);
}, 3000);
});
promise.then(function(data) {
console.log('resolved! ', data);
});
Output
输出量
resolved! 0
Promise {: undefined}
We create a new promise, an object that will be returned from our callback using the new Promise() function. We invoke a .then() function on our promise object which is an asynchronous function and passes our callback to that function. That callback function takes in two parameters, a resolve, and a reject. If our code is successfully executed we get the resolved result and if there is an error we get a reject. Promises are a great way to return values from an asynchronous callback function. Besides we can also chain multiple .then() functions to a promise and avoid messy, difficult to read nested async callbacks. They are widely used today through several promise libraries.
我们创建了一个新的承诺 , 将从我们的回调使用新的无极()函数返回一个对象。 我们在诺言对象上调用一个.then()函数 ,该函数是一个异步函数,并将回调函数传递给该函数。 该回调函数有两个参数,一个是resolve,一个是reject。 如果我们的代码成功执行,我们将得到解决的结果;如果有错误,我们将被拒绝。 承诺是从异步回调函数返回值的好方法。 此外,我们还可以将多个.then()函数链接到一个Promise,避免混乱,难以读取的嵌套异步回调。 今天,它们通过多个Promise库被广泛使用。
翻译自: https://www.includehelp.com/code-snippets/return-a-value-from-a-js-asynchronous-callback-function.aspx