如何在javascript中同步调用一组函数



我正在处理一个javascript项目,该项目需要获取一些数据并进行处理,但我遇到了javascript异步特性的问题。我想做的事情如下。

//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等待函数运行完成,然后再进行下一次调用?

使用承诺:

//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。

您引用的代码将同步运行。JavaScript函数调用是同步的。

因此,我将假设getDataparseData和/或validate涉及异步操作(例如在浏览器中使用ajax,或在NodeJS中使用readFile)。如果是这样,您基本上有两个选项,这两个选项都涉及回调

第一种方法是让这些函数接受它们完成后将调用的回调,例如:

function getData(callback) {
someAsyncOperation(function() {
// Async is done now, call the callback with the data
callback(/*...some data...*/);
});
}

你会这样使用:

getData(function(data) {
// Got the data, do the next thing
});

回调的问题是,它们很难组成,而且语义相当脆弱。因此,承诺的发明是为了给它们更好的语义。在ES2015(又名"ES6")中,或者有一个不错的promise库,它看起来像这样:

function getData(callback) {
return someAsyncOperation();
}

或者如果someAsyncOperation未启用promise,则:

function getData(callback) {
return new Promise(function(resolve, reject) {
someAsyncOperation(function() {
// Async is done now, call the callback with the data
resolve(/*...some data...*/);
// Or if it failed, call `reject` instead
});
});
}

这似乎对你没有多大帮助,但关键之一是可组合性;你的最后一个函数是这样的:

function runner() {
return getData()
.then(parseData) // Yes, there really aren't () on parseData...
.then(validate); // ...or validate
}

用法:

runner()
.then(function(result) {
// It worked, use the result
})
.catch(function(error) {
// It failed
});

下面是一个例子;它只能在支持Promise和ES2015箭头函数的最新浏览器上运行,因为我很懒,用箭头函数编写它,并且没有包含Promise lib:

"use strict";
function getData() {
// Return a promise
return new Promise((resolve, reject) => {
setTimeout(() => {
// Let's fail a third of the time
if (Math.random() < 0.33) {
reject("getData failed");
} else {
resolve('{"msg":"This is the message"}');
}
}, Math.random() * 100);
});
}
function parseData(data) {
// Note that this function is synchronous
return JSON.parse(data);
}
function validate(data) {
// Let's assume validation is synchronous too
// Let's also assume it fails half the time
if (!data || !data.msg || Math.random() < 0.5) {
throw new Error("validation failed");
}
// It's fine
return data;
}
function runner() {
return getData()
.then(parseData)
.then(validate);
}
document.getElementById("the-button").addEventListener(
"click",
function() {
runner()
.then(data => {
console.log("All good! msg: " + data.msg);
})
.catch(error => {
console.error("Failed: ", error && error.message || error);
});
},
false
);
<input type="button" id="the-button" value="Click to test">
(you can test more than once)

您应该更改每个函数以返回一个Promise,这将允许您的最终函数变成:

function runner() {
return Promise.try(getData).then(parseData).then(validate);
}

要做到这一点,每个函数的主体都应该封装在一个新的promise中,比如:

function getData() {
return new Promise(function (res, rej) {
var req = new AjaxRequest(...); // make the request
req.onSuccess = function (data) {
res(data);
};
});
}

这是一个非常粗略的例子,说明了承诺是如何运作的。欲了解更多信息,请查看:

2ality精彩的博客文章:第一部分和第二部分
  • bluebird关于为什么承诺的文档
  • mdn关于JS的Promise类的文档
  • 最新更新