javascript - 从 Javascript Promise 链返回值

标签 javascript node.js promise

这里是现代 JS/Promise 新手。尽管关于这个主题的内容非常多,但我很难找到一个简单问题的答案。

我相信我对 JS Promises 有很好的理解(感谢各种来源,包括 mdn 和 https://spin.atomicobject.com/2016/02/16/how-javascript-promises-work/ )

我经常以最简单的形式使用和生成 Promise,但是我一直在继承的项目中遇到以下模式的方法:

const doAsyncOp = () => 
  $http.get(uri)
    .then(
      value => value,
      reject => //... 
    );

我的大问题是:当您简单地从成功处理程序返回一个值时会发生什么?我需要使用这个方法,并且需要访问客户端代码中的“值”。这在技术上是没有解决的吗?我应该重写实现吗?

最佳答案

My big question is: What happens when you simply return a value from your success handler?

当您从 .then() 处理程序返回一个值时,该值将成为父 Promise 链的解析值:因此,在此代码中:

// utility function that returns a promise that resolves after a delay
function delay(t, v) {
    return new Promise(resolve => {
        setTimeout(resolve.bind(null, v), t);
    });
}

function test() {
    return delay(100, 5).then(val => {
        // this return value becomes the resolved value of the promise chain
        // that is returned from this function
        return 10;
    });
}

test().then(result => {
    // logs 10
    console.log(result);
});

当您运行它时,由于 .then() 处理程序中的 return 10,它将记录 10

.then() 处理程序有四种可能性:

  1. 返回常规值,例如return 10return val。该值成为 promise 链的解析值。如果没有返回值(在 Javascript 中意味着返回值为 undefined),则 Promise 链的解析值为 undefined

  2. 返回最终解决或已经解决的 Promise。此 Promise 会添加到链中,并且 Promise 链会采用该 Promise 的已解决值。

  3. 返回最终拒绝或已被拒绝的 Promise。此 Promise 将添加到链中,并且 Promise 链会承担返回 Promise 的拒绝原因。

  4. 抛出异常。如果在 .then() 处理程序内抛出异常,则 .then() 基础结构将捕获该异常,并将 Promise 链转变为拒绝状态,并将拒绝原因设置为抛出的值。因此,如果您在 .then() 处理程序中抛出 new Error("User not found"),那么该 Promise 链将被拒绝,并以该错误对象作为拒绝原因。

<小时/>

在您的具体代码中:

const doAsyncOp = () => 
  $http.get(uri)
    .then(
      value => value,
      reject => //... 
    );

value => value 没有任何理由。 value 已经是 Promise 的解析值,不需要再次设置。

由于粗箭头函数会自动返回任何单个语句,因此您已经在 doAsyncOp() 函数中从 $http.get().then() 返回了 Promise。所以,你可以这样做:

const doAsyncOp = () => $http.get(uri);

doAsyncOp().then(result => {
   // handle the result here
}).catch(err => {
   // handle error here
});

关于javascript - 从 Javascript Promise 链返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617426/

相关文章:

javascript - 如何显示 JavaScript 数组/对象中的图像?从第一个图像开始,然后单击到下一个图像

node.js - 带或不带 'www' 的域名

javascript - 有更好的方法来编写这段代码吗? -- 在 NodeJS 中使用 Promises 链接 HTTP 请求 - 使用 Await/Async?

javascript - js Sequelize 多个包含不工作的地方

javascript - Angular Bootstrap 如果选项卡处于事件状态,则隐藏外部 div

javascript - react redux 异步操作

javascript - Webpack 不会在 npm run 上生成包文件

debugging - 如何记录和跟踪 NodeJS 事件和事件处理程序调用?

javascript - rsvp.js 如何使用失败回调链处理被拒绝的 promise

javascript - 在 javascript 中递归构建 promise 链 - 内存注意事项