背景:过去两天一直在尝试通过查看本网站和其他网站的各种示例来解决这个问题,但我仍然没有得到它。每当我尝试添加回调或异步/等待时,我都无处可去。我知道这是我的问题所在,但我自己无法解决。
我不是编程背景 :( 我确信它对普通程序员来说是一个快速修复,我远低于那个水平。
当我在“就绪”块中使用console.log(final)时,它可以正常工作,当我转义该块时,如果console.log(final)-或-获取req / server信息,则输出为“未定义”,如果我使用控制台日志(准备好)
const request = require('request');
const ready =
// I know 'request' is deprecated, but given my struggle with async/await (+ callbacks) in general, when I tried switching to axios I found it more confusing.
request({url: 'https://www.website.com', json: true}, function(err, res, returnedData) {
if (err) {
throw err;
}
var filter = returnedData.result.map(entry => entry.instrument_name);
var str = filter.toString();
var addToStr = str.split(",").map(function(a) { return `"trades.` + a + `.raw", `; }).join("");
var neater = addToStr.substr(0, addToStr.length-2);
var final = "[" + neater + "]";
// * * * Below works here but not outside this block* * *
// console.log(final);
});
// console.log(final);
// returns 'final is not defined'
console.log(ready);
// returns server info of GET req endpoint. This is as it is returning before actually returning the data. Not done as async.
module.exports = ready;
下面是 website.com 返回的 JSON 的简短示例。实际调用有 200 多个“结果”对象。
我最终想要实现的是
1) 返回“instrument_name”的所有值
2) 执行一些操作(在每个值的开头添加“trades.”,在每个值的末尾添加“.raw”。
3) 将这些操作放入一个数组中。["trades.BTC-26JUN20-8000-C.raw","trades.BTC-25SEP20-8000-C.raw"]
4) 将此数组导出/发送到另一个文件。
5) 该数组将用作 websocket 连接中使用的另一个请求的一部分。由于数组的值每天都在变化,因此无法将数组硬编码到这个新请求中。
{
"jsonrpc": "2.0",
"result": [
{
"kind": "option",
"is_active": true,
"instrument_name": "26JUN20-8000-C",
"expiration_timestamp": 1593158400000,
"creation_timestamp": 1575305837000,
"contract_size": 1,
},
{
"kind": "option",
"is_active": true,
"instrument_name": "25SEP20-8000-C",
"expiration_timestamp": 1601020800000,
"creation_timestamp": 1569484801000,
"contract_size": 1,
}
],
"usIn": 1591185090022084,
"usOut": 1591185090025382,
"usDiff": 3298,
"testnet": true
}