在nodejs中使用async和await来获得Promise {< pending> } [英] using async and await in nodejs getting Promise { <pending> }

查看:667
本文介绍了在nodejs中使用async和await来获得Promise {< pending> }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下,我能够获得令牌,但无法获得所需的方式,即,我不想打印待处理的promise,并且在tokenDisp.js中运行后,我的输出是:

In my case , i am able to get the token but not the way i wanted ie i do not want to print promise pending and my output after running in tokenDisp.js is :

output: Promise { pending }

 t5Npxk5FfnRTj8iHd8vyyfGxnhXR4KQf

login.js:

  module.exports = async function doLogin() {
  const token = await loginToken();
  const myToken = JSON.parse(token);
  return console.log(myToken);
};

tokenDisp.js:

tokenDisp.js:

 const myToken = require('./login.js);
 myToken();

有人可以帮忙吗?

推荐答案

所有async函数都返回一个Promise,您仍然必须按顺序在async函数的返回值上使用.then()await使用它.如果从async函数返回一个值,它将是返回的Promise的已解析值.如果抛出异常,则该异常将成为拒绝返回的诺言的原因.

All async functions return a promise and you still have to use .then() or await on the return value from the async function in order to use that. If you return a value from your async function, it will be the resolved value of the returned promise. If you throw an exception, the exception will be the reason for the rejection of the returned promise.

在函数内部使用await是异步函数内部的一种便利.它不会神奇地将异步操作变成同步操作.因此,您的函数将返回一个承诺.要从中获得价值,请在其上使用.then().

The use of await inside the function is a convenience INSIDE the async function. It does not magically make an asychronous operation into a synchronous one. So, your function returns a promise. To get the value out of it, use .then() on it.

module.exports = async function doLogin() {
  const token = await loginToken();
  const myToken = JSON.parse(token);
  console.log(myToken);
  return myToken;    // this will be resolved value of returned promise
};

const myToken = require('./login.js);
myToken().then(token => {
    // got token here
}).catch(err => {
    console.log(err);
});


注意:您的login.js模块产生的结果与以这种方式编写的结果相同(不使用asyncawait):


Note: your login.js module produces the same result as if it was written like this (without using async or await):

module.exports = function doLogin() {
  return loginToken().then(token => {
      const myToken = JSON.parse(token);
      console.log(myToken);
      return myToken;    // this will be resolved value of returned promise
  });
};

这篇关于在nodejs中使用async和await来获得Promise {< pending> }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆