1

Can't assign probe function result to w key in newItem object.

Any suggestions?

router.post('/', (req, res) => {
    const newItem = new Item({
        src: req.body.src,
        w: probe(req.body.src, function (err, result) {
            return result.width
            // console.log(result.width)
        })
    });
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Anton Bystrov
  • 134
  • 2
  • 10
  • Possible duplicate of [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) – Heretic Monkey Nov 24 '19 at 13:29

1 Answers1

2

probe seems to be asynchronous, so that code won't work. The recommended approach is to use a Promise & async/await. Without seeing probe definition I can't give you an implementation, but if you don't know how to convert it to a Promise just use util.promisify

const { promisify } = require('util')
const probe = promisify(require('./probe')) // or whatever module

router.post('/', async(req, res) => {

    try {
        const { witdth } = await probe(req.body.src);
        const newItem = new Item({
            src: req.body.src,
            w: witdth
        });
    } catch(e) {
        // Handle error
        res
            .status(500)
            .send('error')
    }
})
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98