Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
Nodejs: process exits while promise is pending

Excerpt of a lambda function using nodejs 12. There is a promise (aws dynamo db document client query) nested inside a promise (node-fetch API request).

The first promise works fine. It executes the request, waits for the promise to resolve, and then enters the .then(...) to execute some code. Next, it executes the database query, but then it exits the whole function without waiting for the promise to resolve, even though there are still callbacks. It doesn't throw errors either. (I know the database query is being executed , as extra logging showed it's status to be <pending>)

When I try var dbscan = await db.scan(...) using await, I get the error await is only valid in async function. But the handler function is already async, and await is working for the fetch promise.

Q: how can I use await inside the .then(...) of the first promise?

Q: why is the process exiting without waiting for the promise to resolve?

exports.myhandler = async (event, context, callback) => {

    var response = await fetch(url, {... my options ...})
    .then(res  => res.text())
    .then(data => {
        // do some stuff with the data ...

        var dbscan = db.scan({...my params ...}).promise()
        .then(res => {
            // do some stuff with result ...
            callback(null, <some message>);
        }).catch(err => {
            console.log(err);
            callback(null, <some message>);
        }); 

    })
    .catch(error => {
    console.log('error', error); 
    callback(null, <some message>);
    }); 
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You have to add async to the beginning of the function in which you want to use await.

.then(async(data) => {
  var dbscan = await ...
})
about 4 years ago · Juan Pablo Isaza Report

0

Since you're already using the async/await-syntax, you shouldn't have to resolve to using .then(..) chains.

You could flatten most of your code like this:

const response = await fetch(url, {... my options ...});
const data = await response.text();
// Do some stuff with the data...
const result = await db.scan({...my params ...});
// Do some stuff with the result...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!