【问题标题】:VueJS Promise is failingVueJS Promise 失败了
【发布时间】:2017-02-09 10:34:32
【问题描述】:

我有一个产品组件和一个产品所有者组件。每个产品都有一个所有者

我要做什么

我通过调用 API 端点接收产品列表。承诺解决后,我有一个产品列表。每个产品都有一个 OwnerID。我正在尝试调用另一个 API 端点来获取所有者的名称并将其分配给当前正在迭代的产品。

到目前为止我的代码

<script>
    var config = require('../config');
    export default {
        data () {
            return {
                products:  [],
            }
        },
        ready () {
            this.getProducts().then(t => {
                console.log(t);
            });
        },
        methods :  {
            getProducts : function() {
                let url = config.API.GetProduct

                this.$http.get(url).then(response=> {
                    this.products = response.data.resource;
                    var p = this.products.map(this.getOwner);
                    return Promise.all(p);

                }, error=> {
                    console.error("An error happened!")
                });
            },
            getOwner : function(product) {
                let url = config.API.GetProductOwnerName.replace('[$$$]', product.OwnerID);
                var p = new Promise();

                this.$http.get(url).then(response => {
                    product.OwnerID = response.data.resource[0].OwnerName;
                    p.resolve(currentObj);
                });

                return p;

            }
        }
        components: {}
    }
</script>

我面临的错误

现在每当我尝试这样做时,我都会不断收到以下错误

Uncaught TypeError: Cannot read property 'then' of undefined
Uncaught (in promise) TypeError: Promise resolver undefined is not a function(…)

有人可以告诉我我在这里做错了什么吗?

谢谢

【问题讨论】:

    标签: vue.js vue-component vue-router


    【解决方案1】:

    您不必重新创建新的 Promise 对象。您可以只返回要传递给下一次调用的对象。

    getProducts: function() {
        let url = config.API.GetProduct
    
        return this.$http.get(url).then(response => {
            this.products = response.data.resource;
            return this.products.map(this.getOwner);
        }, error=> {
            console.error("An error happened!")
        });
    },
    

    【讨论】:

    • 谢谢。但我仍然有同样的问题。
    • 我看到了你的代码。这样,即使我的代码也能正常工作。我真正想做的是,因为我,IMO,有很多我想通过承诺处理的产品。在您的情况下,由于它是一个非常小的对象,因此承诺很快得到解决,因此您会看到消息。我可能错了,但我认为是这样。
    • @Gagan 这与时间无关。 Promise 旨在异步工作。
    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多