Sherin Green
Sherin Green

Reputation: 358

How to send request promise resolve response from another function and that function is call from inside of request promise in Node.js

Actual scenario is i want to return request promise response of test2() from test4() function. because some independent calculation are done in test4() and test2() can not wait for test3() and test4() so i again call test2() from test4() with status flag but the problem is first request promise is overwritten in Memory stack.Is it possible to send request promise response from another function rather than that function.

var status = false;
(async () => {
   var res = await test1();
   console.log('Hi');
   console.log(res);
})();
async function test1() {
    console.log('Call to test2');
    var restest1 = await test2();
    console.log('All Finished', restest1);
    return restest1;
}
function test2() {
    return new Promise(async resolve => {

        if (status) {
            resolve('success');  
        }
        else {

            setTimeout(function () {
                console.log('Call to test3');
                test3();
            }, 5000);

        }
    });
}
function test3() {
    test4();
}
function test4() {
    status = true;
    test2();
    console.log('test4 finished');
}

The problem is console.log('Hi'); console.log(res); not working

Upvotes: 2

Views: 676

Answers (1)

sam
sam

Reputation: 1807

Based on your description and the desired output, I have a quick fix based on your current code structure. The idea is to pass the resolve function along until you really want to call it. So, when you call test2 inside test4 passing the initial resolve function, actually the original promise is resolved and returned. Does it answer your question or I miss your point?

(async () => {
   var res = await test1();
   console.log('Hi');
   console.log(res);
})();
async function test1() {
    console.log('Call to test2');
    var restest1 = await test2();
    console.log('All Finished', restest1);
    return restest1;
}
function test2(resolve) {
    return new Promise(async _resolve => {
        if (resolve) {
            resolve('success');  
        }
        else {

            setTimeout(function () {
                console.log('Call to test3');
                test3(_resolve);
            }, 5000);

        }
    });
}
function test3(resolve) {
    test4(resolve);
}
function test4(resolve) {
    test2(resolve);
    console.log('test4 finished');
}

Upvotes: 2

Related Questions