gpt4 book ai didi

javascript - 履行后将 promise 数组转换为值数组

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

我正在寻找一个函数,该函数将返回 promise 的已解决值。优雅地失败绝对是一种奖励,但这是一个假定的前提条件,即当函数被调用时,promise 已准备好被解析。

当我使用 webdriver.js promise implementation 时它允许类似于下面的队列操作,我不想在队列/链等的语义中迷失太多。仅出于这个原因,这里有一些伪代码来涵盖我想要实现的目标:

var inputs = [...], outputs;
outputs = inputs.map(function(input){
//queue some async tasks to be performed with input
queue.enqueue(...);
//I can't return the *output* value here yet, naturally, so instead
return promise;
});

//now I'll add another task to the same queue
//this means that by the time this task is run
//the async tasks above would have been executed
//and the promises would be "resolvable"... right?
queue.enqueue(function(){
console.log(outputs); //>an array of promises
console.log(doSomeMagic(outputs)); //>resolved values as needed <<<
});

注意:afaik Q.all()不会做我所追求的 - 它需要一个 promise 数组并返回一个数组 promise ,不是它的解析值。我很高兴被证明是错误的。

最佳答案

对于根据问题标题寻找答案的任何其他人,以下内容与 ES 2017+ 一起使用,以获取一组 promise 并返回一组值:

var arrayOfValues = await Promise.all(arrayOfPromises)

关于javascript - 履行后将 promise 数组转换为值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18526824/

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