gpt4 book ai didi

javascript - lodash mapValues 异步

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:42 26 4
gpt4 key购买 nike

在 _.mapValues 中,我想获得一些具有一定延迟的修改值(例如来自数据库),但我遇到了问题:当我在同步模式下修改值时,一切都很好,当我尝试使用 promise 或回调它的工作时不正确(在第一种情况下我得到 Promise 对象,在第二种情况下:未定义的值)。这里有一些简化的例子,我如何重写 mapValues 中的代码来解决这个问题?

'use strict';
const _ = require('lodash');
const Promise = require('bluebird');

let obj = {
one: 1,
two: 2,
};

let increment = (value) => {
return value + 1;
};

let incrementProm = (value) => {
return Promise.resolve(value + 1);
};

let incrementCb = (value, cb) => {
let res = value + 1;
let err = null;
setTimeout(cb.bind(undefined, err, res), 100);
};

let t1 = _.mapValues(obj, (value) => {
return increment(value);
});

let t2 = _.mapValues(obj, (value) => {
return incrementProm(value);
});

let t3 = _.mapValues(obj, (value) => {
let temp;
incrementCb(value, (err, res) => {
temp = res;
});
return temp;
});

console.log('Sync res:');
console.log(t1);
console.log('Promise res:');
console.log(t2);
console.log('Callback res:');
console.log(t3);

最佳答案

您可以使用 bluebird 的 props()函数来解析所有带有 promise 的属性。

Promise.props(_.mapValues(obj, incrementProm))
.then(result => console.log(result));

var obj = {
one: 1,
two: 2
};

var incrementProm = value => Promise.resolve(value + 1);

Promise.props(_.mapValues(obj, incrementProm))
.then(result => console.log(result));
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.1/bluebird.js"></script>

关于javascript - lodash mapValues 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38125401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com