最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Promise with generator? - Stack Overflow

programmeradmin0浏览0评论

I am trying to figure out how to use Promise with generator. For that I am creating function helper to print async task but seems like I am doing it in the wrong way.

const asyncTask = () => new Promise((resolve, reject) => setTimeout(() => resolve('async task'), 1000))

function helper(func){
   return func().next()
}

helper(function* main() { 
 try { 
   const a = yield asyncTask()
   console.log(a)
 } catch(e) { 
   console.error('error happened', e)
 } 
}) 

Getting no output.

I am trying to figure out how to use Promise with generator. For that I am creating function helper to print async task but seems like I am doing it in the wrong way.

const asyncTask = () => new Promise((resolve, reject) => setTimeout(() => resolve('async task'), 1000))

function helper(func){
   return func().next()
}

helper(function* main() { 
 try { 
   const a = yield asyncTask()
   console.log(a)
 } catch(e) { 
   console.error('error happened', e)
 } 
}) 

Getting no output.

Share Improve this question edited Dec 13, 2020 at 11:50 JohnPix asked Dec 13, 2020 at 11:34 JohnPixJohnPix 1,8531 gold badge26 silver badges55 bronze badges 1
  • 1 you can do that but you are confusing between generators and promises. i suggest you to first read tutorial about each of them separately. – Stav Alfi Commented Dec 13, 2020 at 11:40
Add a ment  | 

3 Answers 3

Reset to default 2

I'm not 100% sure what you are trying to achieve. However, if you want to see the output of your promise, you have to await it and log it to the console. Your generator is producing your promise properly but you aren't doing anything with it. This alternative helper() function outputs the result:

async function helper(func){
    let p = func().next().value;
    let output = await p;
    console.log(output);
}

It's generally easier to use asynchronous generators than to use synchronous generators mixed with other async aparatus.

An asynchronous generator works just like a normal generator except:

  • It's prefixed with async, like all async functions
  • next() returns a promise

Here's a simplified example:

let asyncGen = async function*() { 
   yield Promise.resolve('foo');
};
let iterator = asyncGen();
iterator.next().then(result => alert(result.value));

(Note, there's no difference between my Promise.resolve('foo') and your more convoluted promise with a timeout; both are resolved asynchronously - I just kept my example simple.)

You can read more about asynchronous generators in my three-part guide to generators.

You can look at the source code of the co.js to learn more about resolving generators as promises.

The c-promise2 package also has support of generators resolving:

CPromise.from(function*(){
    const value1= yield CPromise.delay(3000, 3);
    // Run promises in parallel using CPromise.all (shortcut syntax)
    const [value2, value3]= yield [CPromise.delay(3000, 4), CPromise.delay(3000, 5)]
    return value1 + value2 + value3;
}).then(function*(value){
    console.log(`Done: ${value}`); // Done: 12
}, err=>{
    console.log(`Failed: ${err}`);
})

Or just use ECMA async generators...

发布评论

评论列表(0)

  1. 暂无评论