gpt4 book ai didi

javascript - 下划线映射行为

转载 作者:行者123 更新时间:2023-12-01 02:56:32 25 4
gpt4 key购买 nike

  a = _.map(b, set);
console.log(a);

function set(item) {
var cpt = item.code;

var options = ["code"];
RS.getCodes(cpt).then(function(response) {
options = options.concat(_.map(response, options));
console.log(ndcOptions);
return options;
});
}

在我的程序中,我想将函数 set 应用于列表 b 中的每个元素以生成一个新列表 a。但是,我认为 set 函数有一些异步执行,当我打印 a 时,它给了我一个空白列表,并且所有 console.log(ndcOptions) ; 在执行 console.log(a); 后执行。我想知道是否有任何方法可以避免 JS 中的这种行为,因此 a 将在执行 console.log(a); 和所有行之前完全赋值之后。

最佳答案

I am wondering if there is any way to avoid this behavior in JS, so a will be assigned completely before the execution of console.log(a); and all the lines after it.

由于您想要对一组项目调用异步函数,因此一般的解决方案是为每个项目创建一个 Promise 并使用 Promise.all 等待所有项目。

对现有代码的更改很小。您需要做的就是从 set 返回 promise 。

Promise.all(_.map(b, set)).then(function(a) {
console.log(a);
// Anything that needs access to `a` needs to be in or called from here
});

function set(item) {
var cpt = item.code;

var options = ["code"];
return RS.getCodes(cpt).then(function(response) {
//^^^^^^ return the created promise
options = options.concat(_.map(response, options));
console.log(ndcOptions);
return options;
});
}

关于javascript - 下划线映射行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673174/

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