简体   繁体   English

如何在异步 function 之外访问 promise 值

[英]How to access promise value outside async function

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?我试图了解承诺、回调等在 node.js 中是如何工作的,特别是在访问 function 之外的值的情况下。我已经花时间在此处查看答案如何从异步调用返回响应? and here call Stripe API with await but every variation I try I always end up with 'subscription' outside the function as undefined.在这里用 await 调用 Stripe API但我尝试的每一个变化我总是以 function 之外的“订阅”作为未定义结束。

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??

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在异步 function之后编写的代码在同步 function 之后执行,但在异步 function 之前完成,因此它将是未定义的,如第一行中设置的那样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.正如您所看到的,控制台日志将在分配之前发生,因为2.花费的时间比3.4.因为其中的5.长。

You should do something like this:你应该这样做:

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

You can also name the function:您还可以命名为 function:

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

functionWithSomeName()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM