【发布时间】:2021-09-07 23:20:14
【问题描述】:
在下面的脚本中,我需要为 listSpaces() 实现一个 Promise,因为它使用 axios 从外部获取数据。
Reading this我不明白
如果条件满足,Promise 将被解决,否则它 会被拒绝
在我的情况下,listSpaces() 可以返回一个空数组或一个包含元素的数组。
问题
他所说的条件是什么?那怎么能和我的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;
});
};
【问题讨论】:
-
“他所说的条件是什么?” - 在他的伪代码中直接出现在该文本行之后的条件 oO 确定
resolve()是否存在的条件或者应该执行reject()回调。 -
我认为您不需要像这样一起使用
.then和await....您可以简单地这样做:const r = await axios.get(...);并在下一行中,没有@987654335 @,你可以这样做r.data.foreach -
"Reading this" - 这是一篇非常糟糕的文章。它甚至不使用the proper terminology for promises。
-
"这怎么可能与我的
listSpaces()联系在一起?" - 一点也不。您没有使用 promise 构造函数,您不必检查条件来决定是要调用resolve还是reject。 -
"在我的情况下,
listSpaces()可以返回一个空数组或包含元素的数组" - 实际上,它没有。它还可以返回状态码。您可能希望throw和new Error使用状态代码和消息来代替。
标签: javascript node.js ecmascript-6 promise axios