【问题标题】:Why console.log is executing before promise is fulfilled in node.js为什么console.log在node.js中实现promise之前执行
【发布时间】:2021-06-25 01:55:27
【问题描述】:

我正在尝试从外部 API 中提取数据,然后创建一组比特币投标价格,然后通过控制台记录输出。问题是控制台日志功能在数据从服务器返回之前执行。这将创建一个空数组。请告诉我如何解决这个问题。

const express = require('express')
const app = express()
const port = 6800
app.listen(port, () => {
    port
})
const GateApi = require('gate-api');
const client = new GateApi.ApiClient();

var _array = [] // store data returned from server

const api = new GateApi.SpotApi(client);  //gate-io api  
const currencyPair = "BTC_USDT"; // string | Currency pair
const opts = {
    'limit': 10 // limit records returned
};

api.listOrderBook(currencyPair, opts).then(value => {
    return value.body.bids.forEach(function(data) {
        _array.push(data);
    });
}, error => console.error(error)).then(console.log(_array))

【问题讨论】:

    标签: node.js api promise cryptocurrency


    【解决方案1】:

    then 的参数应该是一个函数。一旦 promise 完成,该函数就会被执行。

    你不是在传递一个函数,你传递的是console.log()结果

    代替:

    .then(console.log(foo))
    

    你会想要的:

    .then(() => console.log(foo))
    

    【讨论】:

    • 问题已解决。不能投票 - 没有足够的声誉。谢谢
    • @Lawrence Cherone 我回滚了您的编辑。 _array 没有从之前的承诺中返回。
    • np,但是下界是 foo,.then(console.log) 会修复它
    • @LawrenceCherone,如果你想提交它作为答案,那就去吧。 Fwiw,将数组作为参数传递给下一个 Promise 更好,但应该说明的是,.forEach 需要变为 .map 以不增加混淆。
    猜你喜欢
    • 2020-07-13
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多