【问题标题】:Is it possible to run a method after a then() which returns an object in JavaScript? [closed]是否可以在 then() 之后运行一个方法,该方法在 JavaScript 中返回一个对象? [关闭]
【发布时间】:2021-06-21 16:45:38
【问题描述】:

我正在尝试在 .then() 方法运行后立即运行一个操作并返回一个 object。为简单起见,假设我有这段代码 sn-p:

const functionToRunAfterWards = () => { // does stuff };

module.exports = {
  someFunction: ({ someParam }) => {
    
      return anotherFunction.then((someValue) => {
         // do a bunch of stuff
         return someStuff
      })
  },
};

上面的代码 sn-p 有效,但我想在then() 返回someStuff 之后运行function。我尝试在someFunction 之外运行functionToRunAfterWards 函数,但它显示code cannot be accessed。我还尝试添加另一个.then(),但它不起作用......就像这样:

const functionToRunAfterWards = () => { // does stuff };

module.exports = {
  someFunction: ({ someParam }) => {
    
      return anotherFunction.then((someValue) => {
         // do a bunch of stuff
         return someStuff
      }).then(functionToRunAfterWards());
  },
};

你知道如何做到这一点吗?

【问题讨论】:

  • 当你传递给.then()时不要调用你的函数:.then(functionToRunAfterWards);
  • ... 并且可能给它一个参数,否则someStuff 的内容将不可见。
  • 补充@NickParsons 所说的:通过在then(functionToRunAfterwards()) 中调用您的函数,您将函数的返回值 传递给then,而不是函数本身。
  • 你可以做类似then(()=>{functionToRunAfterWards()})
  • .then(fn1) 将返回一个新的承诺,它可以再次被链式.then(fn2) 处理,例如:myPromise.then(fn1).then(fn2)。提供一个函数 fn1 很重要,它需要一个参数(数据,即:someStuff),当然,如果你想用 fn2 处理它,你需要 return 该函数中的数据跟随.then(fn2)(fn2 也必须期待一个参数!)。

标签: javascript node.js arrays object promise


【解决方案1】:

Promises' then 接受一个函数。所以,应该是:

blahBlahPromise.then(functionToRunAfterWards)

【讨论】:

  • 这工作得很好,但我无法接收到someStuff 的值,我该如何获得它?
  • 你能分享更多代码吗?仅供参考,someStuff 始终是承诺链的一部分。所以你需要继续链接blahBlahPromise.then(functionToRunAfterWards).then((someStuff) => { //someStuff passed down from the previous .then call })。你不能同步访问它,因为 JS 是异步的(基本上主线程已经执行,现在它只等待事件回调)
猜你喜欢
  • 1970-01-01
  • 2018-10-01
  • 2014-02-19
  • 2013-08-06
  • 2012-10-27
  • 2020-09-21
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
相关资源
最近更新 更多