1

This is the main.js

const process = require('node:process')
const m1 = require('./m1');
for(var i=process.argv[2];i<=process.argv[3];) {
    i = (m1.f2(i)
        .then(result=>{
            var {fetchedData, processedItr} = result
            console.log(JSON.parse(fetchedData)[0])
            console.log(`processed Iteration ${processedItr}`)
            return processedItr
        })) + 1
}

m1.js

require('dotenv').config()
const https = require('https')
function f2(itr) {
    return new Promise((resolve,reject)=>{
        https.get(process.env.URL+itr,(res)=>{
            let data = ''
            res.on('data',(d)=>{
                data += [d]
            }).on('end',()=>{
                try {
                    if(data!=null) {
                        var result = {
                            fetchedData: data,
                            processedItr: itr
                        }
                        resolve(result)
                    }
                } catch (error) {
                    reject(error)
                }
            })
        }).on('error',(error)=>{
            console.log(error)
        })
    })
}

module.exports = {f2}

.env just contains the URL path

I want to understand how to pass on returned value from a Promise which is inside then block to the main code block (just outside the then block)?

If possible I want to do this in simple for loop as it helps me to switch between different language. With this returning value issue, I noticed that it's difficult to iterate for loop, as I tried to find examples but I couldn't.

DevX
  • 17
  • 1
  • 4
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil Aug 24 '22 at 00:46
  • I saw this post before asking this question, I got the response (return of correct value) from asynchronous call but how to pass it on outside "then block" to use it further down the line. In my case to channel the for loop iterations. – DevX Aug 24 '22 at 00:52
  • 1
    you need to `await` it or return the value from the continuation function. you can't turn async into sync magically – Joe Aug 24 '22 at 01:11
  • @Joe I tried this still getting undefined for next value of i ```for(var i=process.argv[2];i<=process.argv[3];) { i = (async ()=>{ i = await (m1.f2(i) .then(result=>{ var {fetchedData, processedItr} = result console.log(JSON.parse(fetchedData)[0]) console.log(`processed Iteration ${processedItr}`) return processedItr })) + 1 })() }``` – DevX Aug 24 '22 at 01:40

0 Answers0