编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
function spawn(generator) {
    // wrap everything in a promise
    return new Promise((resolve, reject) => {
        const g = generator()

        // run the first step
        step(() => g.next())

        function step(nextFn) {
            const next = runNext(nextFn)
            if (next.done) {
                // finished with success, resolve the promise
                resolve(next.value)
                return
            }
            // not finished, chain off the yielded promise
            // and run next step
            Promise
                .resolve(next.value)
                .then(
                    value => step(() => g.next(value)),
                    err => step(() => g.throw(err))
                )
        }

        function runNext(nextFn) {
            try {
                // resume the generator
                return nextFn()
            } catch (err) {
                // finished with failure, reject the promise
                reject(err)
            }
        }
    })
}

// async function exercise() {
//   const r1 = await new Promise(resolve =>
//   setTimeout(resolve, 500, 'slowest')
// )
//   const r2 = await new Promise(resolve =>
//   setTimeout(resolve, 200, 'slow')
// )
//   return [r1, r2]
// }

// exercise().then(result => console.log(result))
function exercise() {
    return spawn(function* () {
        const r1 = yield new Promise(resolve =>
            setTimeout(resolve, 500, 'slowest')
        )
        const r2 = yield new Promise(resolve =>
            setTimeout(resolve, 200, 'slow')
        )
        return [r1, r2]
    })
}

exercise().then(result => console.log(result))