【问题标题】:Set object key value by function result通过函数结果设置对象键值
【发布时间】:2020-03-19 21:54:57
【问题描述】:

无法将探测函数结果分配给 newItem 对象中的 w 键。

有什么建议吗?

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)
        })
    });

【问题讨论】:

标签: node.js function express object callback


【解决方案1】:

probe 似乎是异步的,因此该代码不起作用。推荐的方法是使用Promise & async/await。没有看到probe 定义我不能给你一个实现,但如果你不知道如何将它转换为Promise 只需使用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')
    }
})

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2022-04-14
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多