简体   繁体   English

在香草Javascript中使用异步/等待的顺序承诺

[英]Sequential promises using async/await in vanilla Javascript

I would like to know how to solve running an array of promises using async, in sequential order, but specifically how to pass the resolved value from one function to the next. 我想知道如何解决使用异步按顺序运行承诺数组的问题,但特别是如何将已解析的值从一个函数传递给下一个函数。

All the examples I have seen so far just show something like this: 到目前为止,我所看到的所有示例都显示如下内容:

const value = await foo();
const value2 = await bar(value);

I'd prefer to do run them all together sequentially from an array, but just not sure how to pass the returned values between them (since I'm trying to use vanilla js async here). 我更愿意从一个数组开始依次运行它们,但是只是不确定如何在它们之间传递返回的值(因为我在这里尝试使用香草js异步)。

You can create a pipeline like this: 您可以这样创建管道:

let fnArray  = [foo,  bar, baz];
let lastResult;
for(let i = 0; i < fnArray.length; i++) {
     lastResult = await fnArray[i](lastResult);
}

Wrap them in a .then() 将它们包装在.then()

foo()
    .then(valueFoo => bar(valueFoo))
    .then(valueBar => AnotherFunc(valueBar))
    .catch(e => { console.log(e)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM