如何将 Promises 与函数的输出一起使用?

How to use Promises with output from a function?

在下面的脚本中,我需要为 listSpaces() 实现一个 Promise,因为它使用 axios 从外部获取数据。

Reading this没看懂

If the condition is met, the Promise will be resolved, otherwise it will be rejected

在我的例子中 listSpaces() 可以 return 空数组或包含元素的数组。

问题

他说的条件是什么?这怎么能和我的 listSpaces() 联系起来?

#!/usr/bin/env node

const yargs = require('yargs');
const listSpaces = require('./functions/cmdListSpaces');

yargs.command({
  command: 'list-spaces',
  describe: 'List spaces',
  type: 'boolean',
  handler(argv) {
    const a = listSpaces();
    a.forEach((v) => {
      console.log(v);
    });
  },
}).argv;

listSpaces()

const toml = require('./toml');
const config = toml('config/kibana.toml');
const axios = require('axios');
    
module.exports = async () => {
  const r = await axios({
    method: 'get',
    url: `${config.Url}api/spaces/space`,
    auth: {
      username: config.Username,
      password: config.Password,
    },
    headers: { 'kbn-xsrf': true },
  })
    .then(response => {
      let a = [];
      response.data.forEach((v) => {
        a.push(v.id);
      });
      return a;
    })
    .catch(error => {
        return error.response.data.statusCode;
  });
};

Reading this, I don't understand

那是一篇非常糟糕的文章。它甚至不使用 .

What condition is it he speaks of?

正如@Andreas 在评论中提到的,他指的是他的伪代码中紧跟在该行文本之后的条件。

And how can that be tied to my listSpaces()?

完全没有。您没有使用 promise 构造函数,您不必检查条件来决定是要调用 resolve 还是 reject.

In my case listSpaces() can either return an empty array or an array with elements

其实不是。它还可以 return 一个状态代码。您可能想要 throw 一个带有状态代码和消息的 new Error

In the below script I need to implement a Promise for listSpaces()

你已经做到了。问题在于您的命令 handler 不期望此承诺,并尝试对其调用 forEach

解决上述问题,您也。选择方法语法:

yargs.command({
  command: 'list-spaces',
  describe: 'List spaces',
  type: 'boolean',
  handler(argv) {
    listSpaces().then(a => {
//              ^^^^^^^^^^
      a.forEach((v) => {
        console.log(v);
      });
    });
  },
}).argv;

function listSpaces() { // no async here!
  return axios({
//^^^^^^
    method: 'get',
    url: `${config.Url}api/spaces/space`,
    auth: {
      username: config.Username,
      password: config.Password,
    },
    headers: { 'kbn-xsrf': true },
  }).then(response => {
    let a = [];
    response.data.forEach((v) => {
      a.push(v.id);
    });
    return a;
  }).catch(error => {
    throw new Error(error.response.data.statusCode);
  });
}

async/await:

yargs.command({
  command: 'list-spaces',
  describe: 'List spaces',
  type: 'boolean',
  async handler(argv) {
//^^^^^
    const a = await listSpaces();
//            ^^^^^
    a.forEach((v) => {
      console.log(v);
    });
  },
}).argv;

async function listSpaces() {
  try {
    const response = await axios({
//  ^^^^^^^^^^^^^^^^^^^^^^
      method: 'get',
      url: `${config.Url}api/spaces/space`,
      auth: {
        username: config.Username,
        password: config.Password,
      },
      headers: { 'kbn-xsrf': true },
    });
    let a = [];
    response.data.forEach((v) => {
      a.push(v.id);
    });
    return a;
  } catch(error) {
//  ^^^^^^^^^^^^
    throw new Error(error.response.data.statusCode);
  }
}