承诺的承诺到简单的承诺? [英] Promise of promise to simple promise?

查看:36
本文介绍了承诺的承诺到简单的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 Promise,通常可以弄清楚如何处理它们,但在这种情况下,我无法弄清楚如何删除一个 Promise 包装级别.

I've been playing with promises, and usually can figure out how to handle them well, but in this situation, I can't figure out how to remove one promise-wrapping level.

代码如下:

let promise2 = promise1.then((nodes) => {
  return Promise.all(nodes.map(n => {

    // findConnections returns a promise
    return this.findConnections(n.get("spotifyData")); 
  }));
});

现在我希望 promise2 包装一个数组,但它没有,它包装了一个包装数组的承诺.如果我想访问数组,我必须这样做:

Now I would expect promise2 to wrap an array, but it doesn't, it wraps a promise wrapping an array. If I want to access the array, I have to do this:

promise2.then(level1 => level1.then(level2 => console.log(level2)));

level1 本身就是一个承诺.

level1 is a promise itself.

当然,我可以使用它,但我发现代码非常难看,我想简化它以便您可以:

Of course, I could work with that, but I find the code very ugly, and I'd like to simplify it so that you can do:

promise2.then(level1 => console.log(level1))

然后直接在那里得到一个数组.

and directly get an array there.

有什么想法吗?

谢谢!

findConnections() 方法:

The findConnections() method:

findConnections: function (node) {
  return Ember.$.get("https://api.spotify.com/v1/artists/" + node.id + "/related-artists").then((data) => {
     return data.artists;
  });
}

推荐答案

level1 本身就是一个承诺.

不,不是.Ember 确实使用了 RSVP,即 Promises/A+ 兼容,这意味着 then 回调永远不会用承诺(或 thenable)调用.他们总是收到一个普通的值.

No it's not. Ember does use RSVP, which is Promises/A+ compatible, and that means that then callbacks are never called with a promise (or thenable). They always receive a plain value.

Promises/A+ 确实要求 then 没有返回嵌套的 Promise.它们总是递归解包.你可以这样做

Promises/A+ does mandate that there are no nested promises returned from then. They are always recursively unwrapped. You can just do

promise2.then(connections => console.log(connections));

如果这真的不起作用,则表明 promise1 不是真正的(或至少不符合标准的)承诺,您应该执行 promise1 = Promise.resolve(promise1) 首先.

If this really doesn't work, that would suggest that promise1 is no real (or at least no standard-conformant) promise, and you should do promise1 = Promise.resolve(promise1) first.

这篇关于承诺的承诺到简单的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆