需要NodeJS中的异步功能

Jon*_*ter 6 javascript asynchronous node.js async-await

我试图在NodeJS中了解async/await.

我在文件中有一个函数如下:

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;
Run Code Online (Sandbox Code Playgroud)

此文件保存twitter.jslib文件夹中

在我的index.js文件中,我有以下内容:

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

let accessToken;

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

console.log(accessToken);
Run Code Online (Sandbox Code Playgroud)

尝试运行此代码时出错:

>   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
Run Code Online (Sandbox Code Playgroud)

我可以不await标记所需的功能async吗?

sle*_*man 11

您的代码已经正确无误.在不改变任何内容的情况下,twitter.js您有两种选择:

  1. 标记为的函数async始终返回promise.因此你可以简单地做:

    const getAccessToken = require('./lib/twitter');
    
    getAccessToken().then(accessToken => {
        console.log(accessToken);
    })
    
    Run Code Online (Sandbox Code Playgroud)
  2. 所有返回promise的函数都可以使用awaited,但是你不能在async标记函数之外使用等待.所以你也可以这样做:

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

async/await关键字不会更改异步函数的行为方式.您仍然不能同步等待异步函数,您只能在异步函数内执行此操作.Async/await只是承诺之上的语法糖.