有条件地在另一个承诺中调用承诺 [英] Calling promise in another promise, conditionally

查看:49
本文介绍了有条件地在另一个承诺中调用承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是我的代码,使用q:

This is basically my code, using q:

let d = Q.defer();
let result = {
    name: 'peter'
};

d.resolve(result);
return d.promise;

但是,我现在需要根据某个条件执行一个步骤.这一步是调用另一个同样返回承诺的对象.所以我有嵌套的承诺,如果这是正确的术语.

However, I now need to perform a step based on a certain condition. This step is calling another object that also returns a promise. So I'm having nested promises, if that's the correct term.

像这样:

let d = Q.defer();
let result = {
    name: 'peter'
};

if (someParameter) {
    otherService.getValue() // Let's say it returns 'mary'
        .then((res) => {
            result.name = res;
        });
}

d.resolve(result);
return d.promise;

但是这不起作用(name 属性仍然是 'peter').可能是因为我内心的承诺在稍后的时间里得到了解决?

This doesn't work however (the name property is still 'peter'). Probably due to the fact that my inner promise is resolved at a later moment?

我也试过这个,但是如果我调用返回承诺的 otherService 就行不通了.如果我只是设置值,它确实有效:

I've also tried this, but it doesn't work if I call the otherService which returns a promise. It does work if I just set the value:

let d = Q.defer();
let result = {
    name: 'peter'
};

d.resolve(result);
return d.promise
    .then((data) => {
        if (someParameter) {
            // Works
            data.name = 'john';

            // Doesn't work
            otherService.getValue()
                .then((res) => {
                    data.name = res;
                });
        }

        return data;
    });

这里的名字将是约翰",而不是玛丽".

Here the name will be 'john', not 'mary'.

显然我误解了承诺,但我无法理解它.

Clearly I'm misunderstanding promises, but I can't wrap my head around it.

推荐答案

使用 Promises 的控制流是...有趣?

Control flow with Promises is...fun?

无论如何,您就快到了,您可以在 Promise 中嵌入 Promise 并将它们链接起来.但是,如果要嵌入它们,则必须返回嵌入的 Promise 链:

Anyway, you are nearly there, you can embed a Promise in a Promise as well as chain them. However, if you are embedding them, you must return the embedded Promise chain:

let d = Q.defer();
let result = {
    name: 'peter'
};

d.resolve(result);
return d.promise
    .then((data) => {
        if (someParameter) {

            // Should work now that we return the Promise
            return otherService.getValue()
                .then((res) => {
                    data.name = res;
                    // And we have to return the data here as well
                    return data;
                });
        }

        return data;
    });

Promise resolve 可以接受一个值或另一个 Promise 并且它将处理流程.因此,当我们在 thenreturn 时,我们返回的值可以是另一个 Promise 或只是一个值.机器会帮我们打开包装.

Promise resolve can take a value or another Promise and it will handle the flow. So, when we return inside a then, the value we are returning can be another Promise or just a value. The machinery will take care of unwrapping for us.

这篇关于有条件地在另一个承诺中调用承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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