简体   繁体   English

使用原生 Promise 的异步事件队列

[英]async event queue using native Promises

I am trying to build "event" queue similar to this: https://stackoverflow.com/a/24932757/6385482我正在尝试构建类似于此的“事件”队列: https : //stackoverflow.com/a/24932757/6385482

but without using any libraries (eg jQuery, Bluebird, Q)但不使用任何库(例如 jQuery、Bluebird、Q)

Example: I have an array示例:我有一个数组

var event = [func1, func2, func3];

...and i want to implement function called 'each' which itaretes 'event' and calls async function sequentially. ...并且我想实现名为“each”的函数,它会调用“event”并按顺序调用异步函数。

Sorry for my English.对不起我的英语不好。

Thank you for your help.感谢您的帮助。

thanks for your reply.感谢您的回复。 Functions are already async, and I need to call func2 after func1 is done (they can't overlap)... I wrote my this function using Bluebird, here is an example:函数已经是异步的,我需要在 func1 完成后调用 func2(它们不能重叠)......我使用 Bluebird 编写了我的这个函数,这是一个例子:

var Bluebird = Promise.noConflict();

var items = [
    function () {
        return new Bluebird(function (resolve, reject) {
            console.log("promise1 pending");
            setTimeout(function () {
                console.log("promise1 fulfilled");
                resolve();
            }, 1000)
        })
    },
    function () {
        return new Bluebird(function (resolve, reject) {
            console.log("promise2 pending");
            setTimeout(function () {
                console.log("promise2 fulfilled");
                resolve();
            }, 500)
        })
    },
];

Bluebird.each(items, function (item, i) {
    return item();
});

This does exactly what I need, first calls "promise1 pending", then "promise1 fulfilled", then "promise2 pending" and "promise2 fulfilled"...这正是我所需要的,首先调用“promise1 挂起”,然后“promise1 实现”,然后“promise2 挂起”和“promise2 实现”......

I tried to write this function with native Prosmises, but I couldn't figure out how.我试图用原生的 Prosmises 编写这个函数,但我不知道怎么做。

Thank you for your help感谢您的帮助

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

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