gpt4 book ai didi

javascript - 如何管理对异步服务的可变调用次数

转载 作者:行者123 更新时间:2023-11-29 10:28:46 25 4
gpt4 key购买 nike

给定:

[1,2,3,4,5] variable array of numbers

我想为数组中的每个数字调用一个异步方法。有哪些方法可以解决这个问题?异步方法的返回类型为 JSON。

我期待的是一个包含调用结果的新 JSON 数组

[{id:1,name:"name1"},
{id:2,name:"name2"},
{id:3,name:"name3"},
{id:4,name:"name4"},
{id:5,name:"name5"}]

最新结果

app.js

( () => {
const result = adapterContext.get([1, 2, 3]);
console.log(result);
})();

service.js

exports.get = list => {
Promise.all(list.map(promise-method-call))
.then(function (response) {
console.log("response", response);
return response;
}).catch(function (error) {
console.log("oops ", error);
});
};

结果

Why is the console.log(result) undefined?

undefined  
response [ '{"hello":1}', '{"hello":2}', '{"hello":3}' ]

最佳答案

你快到了。首先,您需要从您的服务返回 Promise.all 调用:

exports.get = list => {
// Make sure to return the promise!
return Promise.all(list.map(promise-method-call))
.then(function (response) {
console.log("response", response);
return response;
}).catch(function (error) {
console.log("oops ", error);
});
};

然后,在您的应用程序内部需要等待 get 方法完成。有两种方法可以做到这一点:

老派 .then 链接:

(() => {
const result = adapterContext.get([1, 2, 3]).then(result => {
console.log(result);
});
})();

酷 child 异步/等待

(async () => {
const result = await adapterContext.get([1, 2, 3]);
console.log(result);
})();

关于javascript - 如何管理对异步服务的可变调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690200/

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