【问题标题】:Async functions using value from a promise使用 Promise 中的值的异步函数
【发布时间】:2019-11-06 19:08:30
【问题描述】:

所以我知道这个问题被问了很多,但我试图检索一个在承诺中创建的变量。我在这里看到的示例涉及调用 .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);
          });

【问题讨论】:

  • 我认为.filter(task => { 会抛出TypeError,除非之前是非标准的Promise?无论如何,你想使用最终解析值的任何地方都应该放在最终的.then
  • 是的,@CertainPerformance ,体式使用蓝鸟承诺

标签: javascript node.js promise async-await


【解决方案1】:

如果你愿意将你的 .then() 重写为 async/await,这样的东西可能对你有用:

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();

【讨论】:

  • const just = () => doit(); just();
猜你喜欢
  • 2020-08-13
  • 2021-02-15
  • 2021-06-28
  • 2020-01-22
  • 1970-01-01
  • 2019-04-01
  • 2018-01-02
  • 2022-07-22
  • 1970-01-01
相关资源
最近更新 更多