异步函数使用Promise中的值

时间:2019-06-25 01:23:28

标签: javascript node.js promise async-await

所以我知道这个问题经常被问到,但是我正在尝试检索在promise中创建的变量。我在这里看到的示例涉及到调用.then并在那里使用数据,但是我想做的事情涉及一个异步函数-我不能在.then块中使用。

这是我的代码。我正在使用Asana API调出到期的任务列表。成功记录。但是我想将最后一个块中的列表值另存为变量,以便在其他地方使用。

const asana = require('asana');
        const client = asana.Client.create().useAccessToken("xxx");
      client.users.me()
        .then(user => {
            const userId = user.id;
            // The user's "default" workspace is the first one in the list, though
            // any user can have multiple workspaces so you can't always assume this
            // is the one you want to work with.
            const workspaceId = user.workspaces[0].id;
            return client.tasks.findAll({
              assignee: userId,
              workspace: workspaceId,
              completed_since: 'now',
              opt_fields: 'id,name,assignee_status,completed'
            });
          })
          .then(response => {
            // There may be more pages of data, we could stream or return a promise
            // to request those here - for now, let's just return the first page
            // of items.
            return response.data;
          })
          .filter(task => {
            return task.assignee_status === 'today' ||
              task.assignee_status === 'new';
          })
          .then(list => {
            console.log (util.inspect(list, {
              colors: true,
              depth: null
            }));







          })
          .catch(e => {
            console.log(e);
          });

1 个答案:

答案 0 :(得分:1)

如果您愿意以异步/等待的方式重写.then(),那么这样的方法可能对您有用:

const fetch = require('node-fetch');
async function doit() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const json = await response.json();
    console.log(json);
}
doit();