Sag*_*dir 4 javascript asynchronous async-await ecmascript-2017
考虑以下情况:
const waitForEvent = async (api) => {
api.on('eventOne', () => {
return 'eventOne';
})
api.on('eventTwo', () => {
return 'eventTwo';
})
api.on('eventThree', () => {
return 'eventThree';
})
api.load();
}
Run Code Online (Sandbox Code Playgroud)
我要做的是api在异步函数内的变量上设置事件回调,触发api.load()函数,然后返回先发生的事件,在这种情况下要么eventOne|eventTwo|eventThree
问题是,这种语法很糟糕,这个例子不起作用.我找不到任何方法来实现这个使用async/await并且不得不恢复到这样的承诺:
const waitForEvent = (api) => {
return new Promise(resolve) => {
api.on('eventOne', () => {
resolve('eventOne');
})
api.on('eventTwo', () => {
resolve('eventTwo');
})
api.on('eventThree', () => {
resolve('eventThree');
})
api.load();
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,这可以使用async/await来完成吗?无论如何,这可以使用新的async/await es7语法来完成?
由于async/await允许我们以同步方式(自上而下的词汇)编写异步构造,因此实际上没有一种特定方法可以同时执行3行不同的代码(或更准确地说,语句).
对此的理想api是Promise.race.
首先,将您的api回调转换为返回承诺:
const apiPromiseBuilder = (api) => (eventName) => new Promise(resolve => api.on(eventName, () => {
resolve(eventName);
}));
Run Code Online (Sandbox Code Playgroud)
然后你比赛你需要的所有事件:
const waitForEvent = (api) => {
const apiPromise = apiPromiseBuilder(api);
const promiseRace = Promise.race([
apiPromise('eventOne'),
apiPromise('eventTwo'),
apiPromise('eventThree')
]);
api.load();
return promiseRace;
};
Run Code Online (Sandbox Code Playgroud)
或使用async/await:
async function waitForEvent(api) {
const apiPromise = apiPromiseBuilder(api);
const promiseRace = Promise.race([
apiPromise('eventOne'),
apiPromise('eventTwo'),
apiPromise('eventThree')
]);
api.load();
const firstResult = await promiseRace;
return firstResult;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1730 次 |
| 最近记录: |