How to return a value from a regular javascript function that contains a promise chain?

江枫思渺然 提交于 2019-12-08 06:29:59

问题


function bsfir() {
    Parse.Promise.as().then(function() {
        return Parse.Cloud.run('gRFI', {});
    }).then(function(gRFIr) {
        return Parse.Cloud.run('gFI', { });
    }).then(function(gFIR) {
        return gFIR;
    }, function(error) {
        return error;
    });
}

Parse.Cloud.define("bSFI", function(request, response) {
    Parse.Promise.as().then(function() {
        return bsfir();
    }).then(function(bsfirr) {
        response.success(bsfirr);
    }, function(error) {
        response.error("219 error: " + JSON.stringify( error));
    });
});

The goal is to have bsfir() complete execution (i.e. resolve the promise) before handing execution back to the caller, in this case, bSFI().

Calling bSFI() results in executing only a few lines of code in bsfir(). The execution of bSFI() completes almost immediately/instantaneously probably because the promise in bsfir() isn't tied to a return value so when bSFI() calls bsfir(), execution immediately goes to response.success(bsfirr);

Is using Promise.all() in bsfir() a good solution?


回答1:


No, you cannot wait for the promise to resolve before you return. Your task is asynchronous, but the return must happen immediately.

But what you can do is to simply return the promise (from your) itself, and allow your caller to wait for it. In fact, your bSFI() already uses promise anyway, so it is trivial to integrate.

function bsfir() {
    return Parse.Promise.as().then(function() {
//  ^^^^^^
        return Parse.Cloud.run('gRFI', {});
    }).then(function(gRFIr) {
        return Parse.Cloud.run('gFI', {});
    });
}

Parse.Cloud.define("bSFI", function(request, response) {
    Parse.Promise.as().then(bsfir).then(function(bsfirr) {
        response.success(bsfirr);
    }, function(error) {
        response.error("219 error: " + JSON.stringify( error));
    });
});

Notice that you should be able to replace Parse.Promise.as().then(…) by just …() in both functions.



来源:https://stackoverflow.com/questions/33403543/how-to-return-a-value-from-a-regular-javascript-function-that-contains-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!