gpt4 book ai didi

javascript - 在 JavaScript 中实现协程控制流

转载 作者:行者123 更新时间:2023-11-28 11:48:08 27 4
gpt4 key购买 nike

下面实现了一个控制流包装器co,使异步代码仅由yield关键字描述。

这基本上是 ESwhatever 中 async/await 的作用吗?

co(function*() {
console.log('...');
yield one();
console.log('...');
yield two();
})


function co(gFn) {
var g = gFn();

return Promise.resolve()
.then(go);

function go() {
var result = g.next();
if(result.done) {
return;
}
if(isPromise(result.value)) {
return result.value.then(go); // Promises block until resolution.
}
return Promise.resolve(result);
}
}

function isPromise(o) {
return o instanceof Promise;
}

function one() {
return new Promise(resolve => setTimeout(() => (console.log('one'), resolve()), 1000));
}

function two() {
return new Promise(resolve => setTimeout(() => (console.log('two'), resolve()), 1000));
}

编辑:

根据我更新的响应以考虑返回值:

co(function*() {
console.log('...');
const result1 = yield one();
console.log('result1: ', result1);
const result2 = yield two();
console.log('result2: ', result2);
const result3 = yield[one(), two()];
console.log('result3: ', result3);
const result4 = yield{
one: one(),
two: two()
};
console.log('result4: ', result4);
})

function co(gFn) {
var g = gFn();

return Promise.resolve().then(go);

function go() {
var result = g.next(...arguments);
if (isPromise(result.value)) {
return result.value.then(go);
}
if (Array.isArray(result.value)) {
return Promise.all(result.value).then(go);
}
if (isObject(result.value)) {
var o = {};
var promises = Object.keys(result.value).map(k=>result.value[k].then(r=>o[k] = r));
return Promise.all(promises).then(()=>o).then(go);
}
return Promise.resolve(result);
}
}

function isPromise(o) {
return o instanceof Promise;
}

function isObject(val) {
return val && (Object === val.constructor);
}

function one() {
return new Promise(resolve=>setTimeout(()=>(console.log('one'),
resolve('result 1')), 1000));
}

function two() {
return new Promise(resolve=>setTimeout(()=>(console.log('two'),
resolve('result 2')), 1000));
}

最佳答案

Is this basically what async/await does under the hood in ESwhatever?

不是真的。这是做同样事情的不同方法。 async/await 变成的更像是

async function foo() {
const bar = await Bar();
bar++;
const baz = await Baz(bar);
return baz;
}

变成了

function foo() {
return Bar()
.then(bar => {
bar++;
return Baz(bar)
.then(baz => {
return baz;
});
});
}

关于javascript - 在 JavaScript 中实现协程控制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547606/

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