将 Javascript If 语句构造为在函数中同步的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31897192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way of structuring Javascript If statements to be synchronous in a function
提问by bcan001
I'm asking this question so I can learn the 'best practice' way of doing something in javascript. Say I have this code here:
我问这个问题是为了学习在 javascript 中做某事的“最佳实践”方式。假设我在这里有这个代码:
var someFunc = function () {
if (something) {
// do something
}
if (somethingElse) {
// do somethingElse
}
};
The question is what would be the best way to ensure that the 'something' is always ran BEFORE the 'somethingElse'. Since javascript is asynchronous, I understand that I would need some sort of callback system to ensure this. However, is there an easier way to refactor this? What if there are many if statements? What are the best libraries to do something like this cleanly? Thanks in advance.
问题是确保“某事”始终在“其他事”之前运行的最佳方法是什么。由于 javascript 是异步的,我知道我需要某种回调系统来确保这一点。但是,有没有更简单的方法来重构它?如果有很多 if 语句怎么办?干净地做这样的事情的最好的图书馆是什么?提前致谢。
回答by AlexStack
Not all lines of code run asynchronously in Javascript. It depends on your code. For example:
并非所有代码行都在 Javascript 中异步运行。这取决于您的代码。例如:
var someFunc = function () {
if (something) {
console.log('something');
}
if (somethingElse) {
console.log('something else');
}
};
Will always write the following output:
将始终编写以下输出:
something
something else
However if instead of printing the values you are calling a function that will be run later (like an Ajax request or a setTimeout callback), there is no guarantee that your code is run in the exact order. This behaviour depends on the function you are calling. For example the JQuery $.get()
function is asynchronous (which means it will call your function at a later time that is not in your control) like this:
但是,如果您调用的是稍后运行的函数(如 Ajax 请求或 setTimeout 回调)而不是打印值,则无法保证您的代码按确切顺序运行。此行为取决于您正在调用的函数。例如,JQuery$.get()
函数是异步的(这意味着它将在稍后调用您无法控制的函数),如下所示:
var someFunc = function () {
if (something) {
$.get('some-file.txt').done(function (result) {
console.log(result);
});
}
if (somethingElse) {
$.get('some-other-file.txt').done(function (result) {
console.log(result);
});
}
};
The resulting output can be the contents of 'some-file.txt' and 'some-other-file.txt' in any other.
结果输出可以是 'some-file.txt' 和 'some-other-file.txt' 的任何其他内容。
As a rule of thumb whenever you are passing a function to another function (callbacks) you may be using the asynchronousfeature of Javascript.
根据经验,每当您将一个函数传递给另一个函数(回调)时,您可能会使用Javascript的异步功能。
Nested callbacks
嵌套回调
One way to solve this issue is to call the second asynchronous call in the first function:
解决这个问题的一种方法是在第一个函数中调用第二个异步调用:
var someFunc = function () {
if (something) {
$.get('some-file.txt').done(function (result1) {
console.log(result1);
if (somethingElse) {
$.get('some-other-file.txt').done(function (result2) {
console.log(result2);
});
}
});
}
};
But as you might have guessed this code will be hard to read.
但是正如您可能已经猜到的那样,这段代码很难阅读。
Promises to the rescue
拯救的承诺
With Promisesyou can have a code that is easier to read.
使用Promises,您可以拥有更易于阅读的代码。
Let's write the above ugly code with promises:
让我们用 Promise 编写上面丑陋的代码:
var someFunc = function () {
if (something) {
$.get('some-file.txt').then(function (result1) {
console.log(result1);
if (somethingElse) {
return $.get('some-other-file.txt');
}
}).then(function (result2) {
console.log(result2);
});
};
In general, promises make the code more readable and avoid too many nested callbacks. You can chainpromises and it will read like synchronous codebut it actually runs asynchronously.
一般来说,promise 使代码更具可读性并避免过多的嵌套回调。您可以链接承诺,它会读起来像同步代码,但它实际上是异步运行的。
See these questions to get more information:
查看这些问题以获取更多信息:
What's the catch with promises?
承诺有什么问题?
- They are not supported in old browsers (but you can add them with a 3rd party library like ES6 Promise Polyfill.
- Before the promises were officially standardizedevery library had their own implementation which are slightly incompatible (jQuery, Angular, Ember)
- They are a new concept to learn so the learning curve will be a little steep for newcomers.
- 旧浏览器不支持它们(但您可以使用ES6 Promise Polyfill等第三方库添加它们。
- 在 promise 被正式标准化之前,每个库都有自己的实现,它们有点不兼容(jQuery,Angular,Ember)
- 它们是一个需要学习的新概念,因此对于新手来说,学习曲线会有点陡峭。
回答by Aravind
Javascript is not asynchronous.
Javascript 不是异步的。
Provided both the if conditions are satisfied, what is inside the first if will get executed first and then the contents of the second if will be executed.
如果两个if条件都满足,第一个if里面的内容会先执行,然后第二个if的内容会被执行。