1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
const getData = () => new Promise((resolve) => setTimeout(() => resolve("data"), 1000));
async function test() { const data = await getData(); console.log("data: ", data); const data2 = await getData(); console.log("data2: ", data2); return "success"; }
function* testG() { const data = yield getData(); console.log("data: ", data); const data2 = yield getData(); console.log("data2: ", data2); return "success"; }
function asyncToGenerator(generatorFunc) { return function () { const gen = generatorFunc.apply(this, arguments);
return new Promise((resolve, reject) => { function step(key, arg) { let generatorResult; try { generatorResult = gen[key](arg); } catch (error) { return reject(error); }
const { value, done } = generatorResult;
if (done) { return resolve(value); } else { return Promise.resolve(value).then( function onResolve(val) { step("next", val); }, function onReject(err) { step("throw", err); } ); } } step("next"); }); }; }
const testGAsync = asyncToGenerator(testG); testGAsync().then((result) => { console.log(result); });
|