简体   繁体   English

需要NodeJS中的异步功能

[英]Requiring an async function in NodeJS

I am trying to get my head around async/await in NodeJS. 我试图在NodeJS中了解async / await。

I have a function in a file as follows: 我在文件中有一个函数如下:

const getAccessToken = async () => {
  return new Promise((resolve, reject) => {

    const oauthOptions = {
      method: 'POST',
      url: oauthUrl,
      headers: {
        'Authorization': 'Basic ' + oauthToken
      },
      form: {
        grant_type: 'client_credentials'
      }
    };

    request(oauthOptions)
      .then((err, httpResponse, body) => {
        if (err) {
          return reject('ERROR : ' + err);
        }
        return resolve(body.access_token);
      })
      .catch((e) => {
        reject('getAccessToken ERROR : ' + e);
      });
  });
};

module.exports = getAccessToken;

This file is saved as twitter.js in a lib folder 此文件在lib文件夹中保存为twitter.js

In my index.js file I have the following: 在我的index.js文件中,我有以下内容:

const getAccessToken = require('./lib/twitter');

let accessToken;

try {
  accessToken = await getAccessToken();
} catch (e) {
  return console.log(e);
}

console.log(accessToken);

I get an error trying to run this code saying: 尝试运行此代码时出错:

>   accessKey = await getAccessToken();
>                     ^^^^^^^^^^^^^^
> 
> SyntaxError: Unexpected identifier
>     at createScript (vm.js:74:10)
>     at Object.runInThisContext (vm.js:116:10)
>     at Module._compile (module.js:533:28)
>     at Object.Module._extensions..js (module.js:580:10)
>     at Module.load (module.js:503:32)
>     at tryModuleLoad (module.js:466:12)
>     at Function.Module._load (module.js:458:3)
>     at Function.Module.runMain (module.js:605:10)
>     at startup (bootstrap_node.js:158:16)
>     at bootstrap_node.js:575:3

Can I not await the required function as it is marked async ? 我可以不await所需的功能,因为它被标记为async吗?

Your code is already correct. 您的代码已经正确无误。 Without changing anything in twitter.js you have two options to use it: 如果不改变 twitter.js 任何内容 ,您有两种选择:

  1. Functions marked with async always return promises. 标记为async函数始终返回promise。 Therefore you can simply do: 因此你可以简单地做:

     const getAccessToken = require('./lib/twitter'); getAccessToken().then(accessToken => { console.log(accessToken); }) 
  2. All functions that return promises can be awaited upon but you cannot use await outside of an async marked functions. 可以awaited所有返回promise的函数,但不能在async标记函数之外使用等待。 So you can also do: 所以你也可以这样做:

     const getAccessToken = require('./lib/twitter'); (async function () { var accessToken = await getAccessToken(); console.log(accessToken); })(); 

The async/await keywords does not change how async functions behave. async / await关键字不会更改异步函数的行为方式。 You still cannot wait on async functions synchronously, you can only do that inside an asynchronous function. 仍然不能同步等待异步函数,您只能在异步函数内执行此操作。 Async/await is just a syntax sugar on top of promises. Async / await只是承诺之上的语法糖。

You are on the right track, however await can only be used inside an async function. 您处于正确的轨道上,但await只能异步功能中使用。 So you have your structure backwards, and can be easily solved by changing a few things. 因此,您的结构会向后倾斜,并且可以通过更改一些内容轻松解决。 However I suggest you overlook your code and make some structural changes. 但是我建议你忽略你的代码并进行一些结构性的改变。 But here is a working version of your code: 但这是您的代码的工作版本:

const getAccessToken = () => {
  return new Promise((resolve, reject) => {

    const oauthOptions = {
      method: 'POST',
      url: oauthUrl,
      headers: {
        'Authorization': 'Basic ' + oauthToken
      },
      form: {
        grant_type: 'client_credentials'
      }
    };

    request(oauthOptions)
      .then((err, httpResponse, body) => {
        if (err) {
          return reject('ERROR : ' + err);
        }
        return resolve(body.access_token);
      })
      .catch((e) => {
        reject('getAccessToken ERROR : ' + e);
      });
  });
};

module.exports = getAccessToken;

And then: 然后:

const getAccessToken = require('./lib/twitter');

(async function() {
  try {
    let accessToken = await getAccessToken();
    console.log(accessToken);
  } catch (e) {
    return console.log(e);
  }
})()

This is a simple fix to your code to illustrate that you've got it backwards, and some structural changes are in order. 这是对您的代码的一个简单修复,以说明您已经倒退,并且一些结构更改是有序的。

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

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