简体   繁体   中英

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

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 (ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM