如何在javascript中同步调用一组函数
我正在研究一个需要获取一些数据并对其进行处理的javascript项目,但是我在JavaScript的异步特性方面遇到了麻烦.我想要做的是如下所示.
I am working on a javascript project that needs to get some data and process it, but I am having trouble with the asynchronous nature of JavaScript. What I want to be able to do is something like the following.
//The set of functions that I want to call in order
function getData() {
//gets the data
}
function parseData() {
//does some stuff with the data
}
function validate() {
//validates the data
}
//The function that orchestrates these calls
function runner() {
getData();
parseData();
validate();
}
在这里,我希望每个函数在完成下一个调用之前都等待完成,因为我遇到了程序尝试在检索数据之前对其进行验证的情况.但是,我也希望能够从这些函数中返回一个值进行测试,因此我不能让这些函数返回一个布尔值来检查完成情况.如何让javascript等待该函数运行完成,然后再继续下一个调用?
Here I want each function to wait for completion before going on to the next call, as I am running into the situation where the program attempts to validate the data before it has been retrieved. However, I also want to be able to return a value from these functions for testing, so I can't have these functions return a boolean value to check completion. How can I make javascript wait on the function to run to completion before moving on to the next call?
使用承诺:
//The set of functions that I want to call in order
function getData(initialData) {
//gets the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}
function parseData(dataFromGetDataFunction) {
//does some stuff with the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}
function validate(dataFromParseDataFunction) {
//validates the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}
//The function that orchestrates these calls
function runner(initialData) {
return getData(initialData)
.then(parseData)
.then(validate)
}
runner('Hello World!').then(function (dataFromValidateFunction) {
console.log(dataFromValidateFunction);
})
它们不仅易于掌握,而且从代码可读性的角度来看完全有意义.在此处了解更多信息.如果您在浏览器环境中,建议使用此 polyfill.
Not only are they easy to grasp, it makes total sense from a code readability stand point. Read more about them here. If you are in a browser environment, I recommend this polyfill.