一旦我解决了承诺,我无法将值传递到范围之外。 请在这里查看我的代码。
var FullName;
async.series([
function(callback) {
var name = element(by.css('.xyz')).getText().then(function(text) {
console.log("print name" + text);
FullName = text;
console.log("Able to print successfully" + FullName);
});
console.log("Unable to print the name outside" + FullName);
callback();
},
function(callback) {
//I want to retrieve the FullName value to this function.
//but unable to bring the value to this function
console.log("Unable to print the name on the second function too" + FullName)
callback();
}
], function(err) {
done();
})
答案 0 :(得分:0)
我已在代码的第一部分添加了注解来解释问题
var FullName;
async.series([
function(callback) {
var name = element(by.css('.xyz')).getText().then(function(text) {
console.log("print name" + text);
FullName = text;
console.log("Able to print successfully" + FullName);
});
// here, the .then callback hasn't been invoked yet, so FullName is not yet changed
console.log("Unable to print the name outside" + FullName);
// and, you're calling callback() before the .then callback is invoked, so, in the next code, FullName is not changed either
callback();
},
您可以将其重写为
var FullName;
async.series([
function(callback) {
var name = element(by.css('.xyz')).getText().then(function(text) {
console.log("print name" + text);
FullName = text;
console.log("Able to print successfully" + FullName);
callback(); // callback once all asynchronous ops are done
});
},
function(callback) {
console.log("Now able to print the name on the second function " + FullName)
callback();
}
], function(err) {
done();
})
或者,简单地说,没有async.js,因为Promises + async.js从来都不是一个好的组合,你的代码相当于
element(by.css('.xyz')).getText()
.then(function(FullName) {
// do wahtever you need to with FullName in here, note it's NOT global
});