【问题标题】:Can't chain Promises because I need access the scope of the first then in the other two executions [duplicate]无法链接 Promises,因为我需要访问第一个然后在其他两个执行中的范围 [重复]
【发布时间】:2018-09-22 03:02:25
【问题描述】:

我有以下流程要执行:

function doSomething(data, file) {
  createObjectOnDB(data).then(req =>
    upload(res.body.url, file).then(
      getResult(res.body.id)
    )
  })
}

你看到问题了吗?我不能使用.then 链接uploadgetResult,因为它们都在访问req 对象。有什么解决办法吗?

谢谢。

【问题讨论】:

  • 您的意思是getResult 在回调中上传后运行吗?现在你调用getResult 并将返回值传递给.then。可能有助于用伪代码或其他东西准确说明您想要的顺序。
  • 就是这样。我想在上传后运行 getResult。
  • 我当时将第一个声明为 async 函数,但我相信这是一个糟糕的模式
  • 在你的代码中 res 应该是 req?

标签: node.js ecmascript-6 promise


【解决方案1】:

来自this article中的“菜鸟错误#1”

一个更好的风格是这个:

remotedb.allDocs(...).then(function (resultOfAllDocs) {
  return localdb.put(...);
}).then(function (resultOfPut) {
  return localdb.get(...);
}).then(function (resultOfGet) {
  return localdb.put(...);
}).catch(function (err) {
  console.log(err);
});

这叫做组合promise,它是promise的超级大国之一。每个函数只会在前一个 Promise 完成后调用,并且会使用该 Promise 的输出调用。稍后会详细介绍。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 对不起,我的回答有点懒惰,因为我觉得这可能以前回答过很多次。我应该从网站上提取答案。斯塔克先生的编辑效果更好。
【解决方案2】:

使用承诺,您可以将.then() 添加到将返回req 的上传:

function doSomething(data, file) {
  return createObjectOnDB(data)
    .then(req => upload(req.body.url, file).then(() => req))
    .then(req => getResult(req.body.id));
}

更简单的选择是异步/等待:

async function doSomething(data, file) {
  const req = await createObjectOnDB(data);
  await upload(req.body.url, file);
  return await getResult(req.body.id);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2017-04-22
    • 2013-04-08
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多