我可以选择只在if语句的一部分中解决承诺吗



你好,

我在一个模块中有这样设计的功能:

myFunction: function(some args, myBoolean) {
  var deffered = q.defer()
  if(myBool) {
    module.exports.mySecondfunction(args, false, null)
  } else {
    return module.exports.mySecondfunction(args, true, deffered)
},
mySecondFunction: function(some args, myBoolean, myPromise) {
  //Some work here
  if(myBoolean) {
    //Some work
    promise.resolve();
    return myPromise.promise
  }
}
anotherFunction: function(some args) {
  //some work
  if (something) {
    myFunction(some args, true)
  } else {
    myFunction(some args, false).then((data) => {
      //do stuff
    }
  }
}

当另一个功能被触发并转到"其他"部分时,我的服务器抛出一个错误:

TypeError:无法读取未定义的属性"then">

失败的线路是:

myFunction(一些args,false(。然后((data(=>{…

你知道我的代码出了什么问题吗?是否只有在布尔值设置为True的情况下才能承诺函数?

您应该返回两个函数的promise。可以使用类似的东西

anotherFunction: function(some args, myBoolean, myPromise) {
  //some work
  if (something) {
    myFunction(some args, true)
  } else {
    myFunction(some args, false).then((data) => {
      //do stuff
    }
  }
  myPromise.resolve();
  return myPromise.promise;
}

在这种情况下,Promise用于抽象异步/同步方法的变体,如果您需要将anotherFunction更改为真正的异步,这将使您更容易。

BTW:我认为你不应该导出promise,如果你导出了一个函数,当被调用时会返回promise,比如导出myFunction,你可以让你的代码更可重用。

你总是要兑现承诺。

我将继续推荐使用async/await语法。目前您需要babel

async function takesAwhile(otherFirst) {
  if (otherFirst) await doOtherThing();
  return doStuff();    
}

相关内容

最新更新