-1

The following code is working with out superagent call as expected. Block the each callbacks. in the code sendRequest is not acting blocked; I see empty array at the end of program execution.

Any help in resolving would be appreciated. Thanks

process();
async function process() {
    let data = await dataPreparation(collection);
    console.log("data", data);
}


async function sendRequest(endPath, request) {
    return await baseUrl.post(endPath)
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .send(request)
}


async function dataPreparation(collection) {
    let output = [];
    await collection.each(async (items) => {
        let tagName: string = items.name;
        await items.content.each(async (item) => {
            let rawRequest = item.request;
            let endPath = item.endPath;

            let response = await sendRequest(endPath, rawRequest);
            output.push({ 'request': rawRequest, 'endPath': endPath, 'response': response.status });

        })
    });
    return output;
}
  • What sort of object is `items.content`? – CertainPerformance Aug 13 '19 at 05:03
  • Lots of code we don't know what it does. Does `baseUrl.post().set().set().send()` return a promise? Does `collection.each()` return a promise? Is `collection.each()` coded for a callback the returns a promise so that it will actually wait for the `await` inside that callback? Does `sendRequest()` return a promise? Also, `return await fn()` is equivalent to `return fn()` if `fn()` returns a promise and the `await` is pointless if `fn()` doesn't return a promise. – jfriend00 Aug 13 '19 at 05:10
  • And, does `items.content.each()` return a promise? I'm asking all of this because `await` does NOTHING useful if you're not awaiting a promise which seems to be a very, very common beginners mistake (thinking that `await` will wait for anything, regardless of what you give it). – jfriend00 Aug 13 '19 at 05:11
  • I'm betting the `.each` is the main problem, but without context, it's impossible to say – CertainPerformance Aug 13 '19 at 05:12

1 Answers1

0

From yur problem statement, i understood that you are having problem with the foreach callbacks, i have converted it into for loops, i think it should work.

async function dataPreparation(collection) {
    let output = [];
    for (var items of collection) {
        let tagName: string = items.name;
        for (var item of items.content) {
            let rawRequest = item.request;
            let endPath = item.endPath;
            let response = await sendRequest(endPath, rawRequest);
            output.push({ 'request': rawRequest, 'endPath': endPath, 'response': response.status });
        }
    };
    return output;
}
Nayan Patel
  • 1,683
  • 25
  • 27