且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待并且在灯设置为绿色之前不执行功能

更新时间:2023-01-23 18:29:08

你没有告诉我们任何关于你的灯的 API,所以我只能猜测它是什么样的.假设它是一个事件驱动模型,您可以将其转换为承诺,然后执行以下操作:

You haven't told us anything about the API for your light so I can only guess what it's like. Presuming it's an event driven model, you can convert it to a promise, and do this:

function waitForGreenLight() {
    return new Promise(function (resolve) {
        $window.addEventListener("message", function (event) {
           if (event.data.req === "task2ReturnFromB") {
               resolve(event.data) 
           }
        }, { once: true });
    });
}

return doTask1()
    .then(waitForGreenLight)
    .then(doTask2);

如果你的灯不提供事件,你可以有一个 waitForGreenLight 定期轮询它直到它变成绿色.使用 waitForGreenLight 的代码将保持不变.

If your light doesn't provide events, you could have a waitForGreenLight that periodically polls it until it's green. The code to use waitForGreenLight would remain the same.

function waitForGreenLight() {
    return new Promise(function (resolve) {
        var handle = setInterval(function () { 
            if (myLight.color === 'green') { 
                resolve();
                clearInterval(handle);
            }
        }, 100);
    });
}