如何返回Q javascript中的最后一个值

How to return the last value in Q javascript

本文关键字:javascript 最后一个 何返回 返回      更新时间:2023-09-26

嗨,我是用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);
    });
}