gpt4 book ai didi

javascript - Lodash中函数同步返回

转载 作者:行者123 更新时间:2023-12-03 02:53:24 25 4
gpt4 key购买 nike

在我的 AngularJS 应用程序中,我有以下变量:

var meals = _.times(mealCount, function(index) {
return new MealPlanResource({
dayId: dayId,
userFriendlyMealNumber: index + 1,
items: [],
});
});

如何才能使函数的下一行在 _.times 完全执行之前不会运行?

我尝试过:

var mealsDeferred = $q.defer();
var meals = mealsDeferred.resolve(getUpdatedMeals());

function getUpdatedMeals() {
_.times(mealCount, function(index) {
return new MealPlanResource({
dayId: dayId,
userFriendlyMealNumber: index + 1,
items: [],
});
});
}

以及:

var meals;
setTimeout(function() {
_.times(mealCount, function(index) {
return new MealPlanResource({
dayId: dayId,
userFriendlyMealNumber: index + 1,
items: [],
});
});
}, 100);

两者都将餐食返回为“未定义”。

最佳答案

假设您的 _.times() 函数是 LoDash 中的函数,那么您的代码应该按原样工作。

_.times() 是一个同步函数。它不是异步的。它在返回值之前完成所有执行。您不需要使用 promise ,它们不会给您带来任何好处。

这是您的代码的工作示例:

function MealPlanResource( args ) {
_.assign( this, args );
}

var mealCount = 3;
var dayId = 1;

var meals = _.times(mealCount, function(index) {
return new MealPlanResource({
dayId: dayId,
userFriendlyMealNumber: index + 1,
items: [],
});
});

console.log( meals );
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

您能否将其与实际代码进行比较,看看有什么不同?

关于javascript - Lodash中函数同步返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47740869/

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