如何将数据与承诺一起返回

时间:2017-10-14 10:06:32

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

此功能按顺序处理股票账户数据,如状态机,以便下达卖单。

我需要将帐户数据传递给每个州,我不想将其存储在全局变量中。我如何实现这一目标?我不恰当地使用承诺吗?

注意每次调用如get_account,delete_order都是返回承诺的异步调用。他们不应该传递无关的数据。

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
    });
}

3 个答案:

答案 0 :(得分:2)

做什么

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

then(([data, account]) => {...})

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

return 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 / await

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;
  }
}

答案 1 :(得分:0)

从第一个account返回.then()以访问链接account

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

答案 2 :(得分:-1)

您可以执行以下操作:

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

因此将account变量保留在本地范围内。