gpt4 book ai didi

javascript - 完成后如何获取多个异步调用的返回值?

转载 作者:行者123 更新时间:2023-11-30 10:01:43 24 4
gpt4 key购买 nike

我正在使用异步的第 3 方 API 方法。我有需要传递给这个异步方法的项目列表,我想在所有异步调用完成后打印出所有返回结果的结果。我知道我可以使用回调来完成此操作。但我无法让它工作。它什么都不打印。显然我在这里使用回调错误。是的,我在这里读到回调:https://github.com/maxogden/art-of-node#callbacks .有很好的例子。但不确定如何使其与异步调用数组一起使用并组合结果。

var resultArray = [];
var items = ["one", "two", "three"];
getResult(items, printResult);
function printResult()
{
for(let j=0; j < resultArray.length; j++)
{
console.log(resultArray[j]);
}
}
function getResult(items, callback)
{
for(let i=0; i<items.length; i++)
{
apiClient.findItem(items[i], function (error, item){
resultArray.push(item.key);
});
}
}

最佳答案

正如@JeffreyAGochin 所指出的,您可以用 promises 代替它。如果你不想那样做并且想坚持使用回调(我不推荐),你可以使用优秀的 async .

function getResult(item, done) {
apiClient.findItem(item, done);
}

async.each(items, getResult, function (error, results) {
// if error is null, then all of your results are in 'results'
if(error !== null) throw error;
results.forEach(function(result) {
console.log(result);
});
});

示例 promise 实现(我假设您使用的是 ES6,因此由于您的 let 而原生具有 Promise)

// When you are using promises natively (apparently these have performance implications, see comments) your code looks like this:

function getResult(item) {
return new Promise(function(resolve, reject) {
apiClient.findItem(item, function(error, foundItem) {
if(error) return reject(error);
resolve(foundItem);
});
});
}

// If you use the excellent bluebird library though (which is pretty common actually), it looks more like this.
let apiClient = Bluebird.promisifyAll(apiClient);
function getResult(item) { return apiClient.getItemAsync(item); }

var resultsPromise = Promise.all(items.map(getResult));
resultsPromise.then(function(results) {
results.forEach(function(result) {
console.log(result);
});
});

至于为什么这么多人建议promises;这是因为他们的作曲要好得多。还有一些很棒的库支持 promise ,例如 highland (与上面的 async 也是同一作者)将 promise 视为第一类值。很难像这样处理回调,因为没有真正的方法来“传递它们”

关于javascript - 完成后如何获取多个异步调用的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280888/

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