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

javascript - How to access promise value outside async function - Stack Overflow

programmeradmin1浏览0评论

I'm trying to understand how promises, callbacks etc work in node.js, particularly in the case of accessing the value outside of the function. I've spent time going through the answers here How do I return the response from an asynchronous call? and here call Stripe API with await but every variation I try I always end up with 'subscription' outside the function as undefined.

Thanks

let subscription;
async function getSub(){
    subscription = await stripe.subscriptions.retrieve('sub_HurxwcQoCIH7jv');
    // code here only executes _after_ the request is done?
    return subscription
}
getSub()
console.log("subscription: ", subscription) // subscription undefined??

I'm trying to understand how promises, callbacks etc work in node.js, particularly in the case of accessing the value outside of the function. I've spent time going through the answers here How do I return the response from an asynchronous call? and here call Stripe API with await but every variation I try I always end up with 'subscription' outside the function as undefined.

Thanks

let subscription;
async function getSub(){
    subscription = await stripe.subscriptions.retrieve('sub_HurxwcQoCIH7jv');
    // code here only executes _after_ the request is done?
    return subscription
}
getSub()
console.log("subscription: ", subscription) // subscription undefined??
Share Improve this question asked Aug 30, 2020 at 6:07 quietplacequietplace 5391 gold badge5 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

There are 2 ways you can get a response

getSub()
.then(subscription => {
    console.log("subscription: ", subscription);
});

Or

const funcA = async() {
    const subscription  = await getSub();
    console.log("subscription: ", subscription);
}
funcA();

The code written after the async function is executes AFTER the sync function but getting done BEFORE the async function so it will be undefined as set in the first line let subscription // undefined

Lets cut it into pieces and number the chronology of happens:

1. let subscription;
2. async function getSub(){
    5. subscription = await stripe.subscriptions.retrieve('sub_HurxwcQoCIH7jv');
    // code here only executes _after_ the request is done?
    6. return subscription
}
3. getSub()
4. console.log("subscription: ", subscription) // subscription undefined??

So as you can see, the console log will happen BEFORE the assignment because 2. takes longer than 3. and 4. because of 5. in it.

You should do something like this:

(async () => {
  const sub = await stripe.subscriptions.retrieve('sub_HurxwcQoCIH7jv')
  console.log(sub) //
})()

You can also name the function:

const functionWithSomeName = async () => {
  const sub = await ...CODE HERE...
  console.log(sub)
}

functionWithSomeName()
发布评论

评论列表(0)

  1. 暂无评论