基于变量数组按顺序执行异步方法



我有一系列答案。

var answers = ['Yes', 'No', 'Yes']; 

我必须在网络测验中输入这些答案,其中问题会按顺序弹出。我使用硒驱动程序感知问题。

我使用以下方法输入答案。

var answerQuestion = function(driver, answer) {
var defer = q.defer();
var elementXPath = "//*[contains(@class, 'quizAnswer’)]";
var delay = 2000;
return driver.waintUntilVisible(elementXPath, delay).sendKeys(answer);
};

现在我想按顺序对answers数组中的每个答案执行上述方法,因为在回答当前问题之前,下一个问题不会出现。

一个简单的foreach循环在这里失败。

function submitAnswers(driver) {
answers.forEach(function(answer) {
answerQuestion(driver, answer);
});
}

那么如何基于变量数组按顺序执行异步方法。

由于硒函数返回承诺,因此您必须按顺序一个接一个地解决。

对于您的情况,以下应该会神奇。

var answerQuestion = function(driver, answer) {
return function() {
var defer = q.defer();
var elementXPath = "//*[contains(@class, 'quizAnswer’)]";
var delay = 2000;
return driver.waintUntilVisible(elementXPath,delay).sendKeys(answer);
};
function submitAnswers(driver) {
return answers.reduce((previous, answer) => {
return previous.then(answerQuestion(driver, answer);
}, Promise.resolve());
}

起初answerQuestion应该是有希望的:

function answerQuestion(driver, answer) {
var elementXPath = "//*[contains(@class, 'quizAnswer’)]";
var delay = 2000;
return driver.waintUntilVisible(elementXPath, delay).sendKeys(answer);
}

那么这很容易:

function submitAnswers(driver, position = 0) {
if(position >= answers.length) return;
return answerQuestion(answers[position]).then(function() {
return submitAnswers(driver, position + 1);
});
}

或者,如果您可以使用async/await

async function submitAnswers(driver, answers) {
for(const answer of answers)
await answerQuestion(answer);
}

我终于想出了一个办法。 感谢戴夫·塞迪亚

var answers = ['Yes', 'No', 'Yes'];
var answerQuestion = function(driver, answer) {
var elementXPath = "//*[contains(@class, 'quizAnswer’)]";
return driver.waintUntilVisible(elementXPath, delay).sendKeys(answer);
};
function submitAnswers(driver) {
var chain = q.when();
answers.forEach(function(answer) {
chain = chain.then(function() {
return answerQuestion(driver, answer);
});
});
}

相关内容

  • 没有找到相关文章

最新更新