javascript - 如何随 promise 一起返回数据

标签 javascript node.js es6-promise state-machine

此函数像状态机一样按顺序处理股票帐户数据,以便下达卖出订单。

我需要将帐户数据传递到每个状态,并且我不想将其存储在全局变量中。我该如何实现这一目标?我是否不恰本地使用了 Promise?

请注意,每个调用(例如 get_account、delete_order)都是返回 Promise 的异步调用。他们不应该传递不相关的数据。

function sell_stocks(){
    get_account_info().then(account => {
        if (account.orders.length > 0){
            return delete_orders(account.orders);
        } else {
            return "continue";
        }
    }).then(data => {
        // Now I need variable "account"
        place_sell_order(account.volume); //account undefined
    }).catch(msg => {
        //handle error
    });
}

最佳答案

做什么

返回delete_orders(account.orders).then((data) => [data,account]);

还有

then(([数据, 帐户]) => {...})

或者如果您只想要帐户数据

返回delete_orders(account.orders).then(() => account);

还有

function sell_stocks(){
    get_account_info().then(account => {
        if (account.orders.length > 0){
            return delete_orders(account.orders).then(()=> account);
        } else {
            return account;
        }
    }).then(account => {
        place_sell_order(account.volume);
    }).catch(msg => {
        //handle error
    });
}

或者使用异步/等待

async function sell_stocks(){
  try {
    const account = await get_account_info();
    if (account.orders.length > 0) {
      await delete_orders(account.orders)
    }
    return place_sell_order(account.volume);
  } catch (e) {
    console.log(`At sell_stocks ${e}`);
    return null;
  }
}

关于javascript - 如何随 promise 一起返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743286/

相关文章:

sql - node.js 登录无法使用 azure sql 数据库

javascript - ExpressJS 响应中间件

javascript - typescript 提示 promise.then

webpack - 使用 Promise.all() 从 Axios 转换为 Fetch

javascript - 如何在node js中的readline.on函数下使用await函数

javascript - Web 应用程序控制台错误 : firebase-auth. js :1 Uncaught Error: Cannot instantiate firebase-auth - be sure to load firebase-app. js 首先

javascript - 添加 Integer 创建条目后的 ERR_EMPTY_RESPONSE node.js

node.js - 环回上的 Kurento 媒体管道覆盖图像不起作用

javascript - 如何在时间变化时旋转图像?

javascript - jquery 检查属性元素值