您如何使用回调来保证顺序执行? [英] How can you use a callback to guarantee sequential execution?

查看:185
本文介绍了您如何使用回调来保证顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设法绕过回调,但我不明白如何保证一个语句将在之后(按时间)执行的回调 未知时间.我不在乎 promise,await,async等,而只是在尝试学习的简单回调.

I am trying to wrap my head around callbacks and I do not understand how callbacks guarantee that a statement will execute after(in terms of time) another statement which takes an unknown amount of time. I do not care about promises,await,async, etc but just plain callbacks as I am trying to learn.

例如,在下面的示例中,我的方法将在发生未知时间事件之前执行回调.我可以看到因为发生了事件,如何使用回调执行某些操作,但是不是如何使用回调来保证执行某些操作之后(就时间而言),其他内容已完成执行并返回了有意义的内容.

For example below, my method will execute the callback before the unknown time event has occured. I can see how callbacks can be used to execute something because an event occurred but not how they can be used to guarantee that something will be executed after(in terms of time) something else has finished executing and returned something meaningful.

function foo(callback) {
    setTimeout(() => console.log("Do something with unknown time"),
        2000);
    callback();
}

function callback() {
    console.log("Execute callback");
}

foo(callback);

所以我要问的是,可以使用回调来确保时域中的执行顺序吗?还是他们唯一的目的就是响应事件?

So what I am asking is can callbacks be used to guarantee execution sequence in the time domain ? Or is their only purpose responding to events ?

推荐答案

您问了两个问题

  1. 是否保证回调执行顺序?

  1. Is callback execution sequence guaranteed?

回调仅响应事件吗?

答案

  1. 是的.

据我了解,callback只是在调用另一个要立即运行的函数(被调用时)

From my understanding, callback is just calling another function to be run now (when it is called)

保证在您调用它时立即运行.

It is guarantee to run immediately when you call it.

要确保在触发回调之前调用了某些内容,只需在进行回调之前先将要调用的内容放在第一位即可.

To ensure something is called before the callback is triggered, simply put the things you want to call execute first before callback is conducted.

例如从您的代码中进行一些修改,可以确保在console.log执行后可以运行回调.

e.g. from your code, by modify it a bit, callback is guarantee to run after the console.log is executed.

function foo(callback) {
    setTimeout(() => {
        console.log("Do something with unknown time");
        callback();
    }, 2000);
}

function callback() {
    console.log("Execute callback");
}

foo(callback);

setTimeout推迟执行,与回调方法无关.

It is the setTimeout which defers the execution, and is not related to callback methodology.

  1. 当然,回调可以用作响应事件的回调,就像elem.addEventListener("click", callback);一样.但不仅如此.
  1. Sure, callback can be used as a callback to respond to event, just like elem.addEventListener("click", callback);. But not only that.

下面将说明一个简单的示例.

A simple example will be illustrated below.

例如

var map = function(arr, callback) {
  var result = [];
  for (var i = 0, len = arr.length; i < len; i++) {
    result.push(callback(arr[i]));
  }
  return result;
};

map([0, 1, 2, 3], function(item) {
  return item * 2;
})

已编辑

此修改是指

Edited

This edit is referring to

例如,如果我正在进行数据库调用,我不知道要检索数据将花费多少时间.如果在它到达之前尝试访问它,则会收到错误消息.

For example, if I am making a database call, I do not know how much time it is going to take for the data to be retrieved. If i try to access it before it has arrived, I'll get an error.

调用数据库与异步http请求没有什么不同.因此,在这里,我将使用XMLHttpRequest来演示如何使用回调来确保这一点.但是通常,这些是浏览器或node.js中已经提供的功能.因此,您无需自己编写.当然,为了防止回调地狱,我个人更喜欢使用Promiseasync/await.但这有点不合时宜.

Calling a database, is by no means different from an async http request. So here, I will use XMLHttpRequest to demonstrate how to use callback to ensure this. But normally, these are features provided in browser or node.js already. So you do not need to write it by your own. Of course, to prevent callback hell, I will personally prefer use of Promise or async/await. But this is a bit out of topic.

因此,让我们看看XMLHttpRequest如何使用回调来处理异步任务.

So let see how XMLHttpRequest can use callback to handle async task.

var sendRequest = function(callback) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       callback(this); 
    }
  };
  xhttp.open("GET", "filename", true);
  xhttp.send();
}

,您可以使用回调来处理异步事件.有时你不知道什么时候会发生.而基本原理是从我在答案1中说过的示例得出的.

and you can use callback to handle async event. Sometime you dont know when it will happen. And the basic idea how it works is from the example I have said in answer 1.

这篇关于您如何使用回调来保证顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆