如何返回Q javascript中的最后一个值
How to return the last value in Q javascript
嗨,我是用javascript编写promise的新手。我想从func1返回一个值,该值由然后(使用q)调用其他函数来解析该值,然后通过下一个函数传递给组成。问题是我想返回函数1中的最后一个值。所以我可以在调用者函数中使用它。但init值只是返回undefined。以下是代码:
function func1(string1, string2) {
othermodule
.otherfunc1(string1)
.then(function(outputstring1) {
var params = othermodule.otherfunc2(outputstring1,string2);
return params;
})
.then(anotherfunc)
.then(anotherfunc2)
.then(function (data) {
console.log(data);
// outputs data
return data;
});
}
function caller() {
var initValue = 0;
initValue = func1(string1,string2);
console.log('init value = '+initValue);
//init value = undefined
}
用javascript编写异步代码是有害的,这意味着所有调用异步代码的代码本身都必须是异步的。
您的代码可以重写为:
function func1(string1, string2) {
return Q.fcall(othermodule.otherfunc1, string1)
.then(function(outputstring1) {
var params = othermodule.otherfunc2(outputstring1, string2);
return params;
})
.then(anotherfunc)
.then(anotherfunc2)
.then(function(data) {
console.log(data);
return data;
});
}
function caller() {
return func1(string1, string2).then(function(initValue) {
console.log('init value = ' + initValue);
});
}
返回func1中的promise
然后在调用者中使用.then来获取"返回"值
function func1(string1, string2) {
return othermodule.otherfunc1(string1)
.then(function(outputstring1) {
var params = othermodule.otherfunc2(outputstring1, string2);
return params;
})
.then(anotherfunc)
.then(anotherfunc2)
.then(function(data) {
console.log(data);
return data;
});
}
function caller() {
func1(string1, string2).then(function(initValue) {
console.log('init value = ' + initValue);
});
}
相关文章:
- 尝试使用Javascript正则表达式来获取“&"分隔文本,无论它是否's是最后一个值
- 如何使用JavaScript forloop从JSON中删除最后一个逗号
- Javascript:删除冒号的最后一个字符
- Javascript/jQuery替换tamil语言输入框中的最后一个单词
- 使用javascript替换字符串中除第一个和最后一个之外的所有字符
- jQuery/Javascript>on单击将文本放置在最后一个已知的光标位置
- 如何使用javascript获取最后一个全天时间戳
- ..的Javascript..循环中的对象没有在最后一个属性上运行
- JavaScript 不会替换字符串的最后一个符号
- JavaScript,数组和函数 - 只有数组的最后一个元素有效
- Javascript 切掉最后一个字符,如果有 2 个
- 在 Javascript 中获取字符串中的最后一个符号时值错误
- Regex:使用javascript测试最后一个单词后的url中是否存在最后一个斜杠
- 使用javascript删除特定HTML实体(breadcrumb)的最后一个实例
- 在JavaScript数组中查找最后一个元素的计算效率最高的方法
- 使用JavaScript替换字符串的最后一个字符
- 使用JavaScript匹配URL中的最后一个单词
- 如何在Javascript中的对象数组的最后一个对象之后附加几个新对象
- jQuery使用最后一个参数在Javascript循环中单击绑定函数
- 如何记住asp.net中最后一个被调用的JavaScript函数