简体   繁体   English

其他功能完成后如何调用一个功能?

[英]How to call a function after the other function is done?

My problem is that i coded a simple overstock function for my game-items trading site ( site working with socket.io! ). 我的问题是我为我的游戏项目交易网站( 与socket.io!一起使用的网站 )编写了一个简单的积压功能。 And when the site is loading, two functions getting user and site inventories with items and listing them into two boxes, but the user inv loads faster and info about overstock comes later as the bot inv is loaded. 当网站加载时,有两个功能可以获取用户和网站的物品清单并将它们列出到两个框中,但是用户inv加载速度更快,而有关bot inv加载的信息则稍后出现。 I need to execute the "get user inventory" function after the "get bot inventory" function is fully done. 在完成“获取机器人清单”功能后,我需要执行“获取用户清单”功能。 I tried to set a sleep function between them, but it worked only for the main function that loading whole functions. 我试图在它们之间设置一个睡眠功能,但是它仅适用于加载整个功能的主要功能。 In other words sleep(2000) delays loading both inventories when it set between this two functions. 换句话说,sleep(2000)在这两个功能之间设置时会延迟加载两个清单。 sorry for my bad english :-D 对不起,我的英语不好:-D

Aaand there is my code (i left only important part): Aaand有我的代码(我只留下了重要的部分):

io.on('connection', (socket) => {
    var userObject = false
    if (
        typeof socket.handshake.session.passport !== 'undefined' &&
        typeof socket.handshake.session.passport.user !== 'undefined' &&
        typeof socket.handshake.session.passport.user.id !== 'undefined'
    ) {
        userObject = socket.handshake.session.passport.user
    }

    socket.emit('site', config.site)
    socket.emit('user', userObject)

    socket.on('get bot inv', (id) => {
        Trade.getInventory(config.bots[id].steamID64, config.appID, config.contextID, (err, data) => {
            socket.emit('bot inv', { error: err, items: data })
        })
    })
   socket.on('get user inv', (steamID64) => {
        Trade.getInventory(steamID64, config.appID, config.contextID, (err, data) => {
            socket.emit('user inv', { error: err, items: data })
        })
    })
    socket.on('get bots inv', () => {
        const params = []
        Object.keys(config.bots).forEach((index) => {
            const bot = config.bots[index]
            params.push({
                id: index,
                steamID64: bot.steamID64,
                appID: config.appID,
                contextID: config.contextID,
            })
        })

        Trade.getInventories(params, (data) => {
            socket.emit('bots inv', data)
            socket.emit('bots floats', Trade.getFloatValues())
        })
    })
})

Look into promises. 研究诺言。

var promise1 = new Promsie((resolve, reject) => {
  socket.on('get bot inv', (id) => {
        Trade.getInventory(config.bots[id].steamID64, config.appID, config.contextID, (err, data) => {
            socket.emit('bot inv', { error: err, items: data })
            resolve();
        })
    })
})

var promise2 = new Promsie((resolve, reject) => {
 socket.on('get user inv', (steamID64) => {
        Trade.getInventory(steamID64, config.appID, config.contextID, (err, data) => {
            socket.emit('user inv', { error: err, items: data })
            resolve();
        })
    })
})

If you want to wait until one finishes 如果您要等到一个完成

promise1.then(() => {return promise2});

If you want N things to execute and await all of them, use the following 如果您想执行N项并等待所有这些,请使用以下命令

Promise.all([promise1, promise2]).then(() => {execute something else});

For further documentation: 有关更多文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

You might want to use promises. 您可能要使用诺言。 At first, encapsulate the socket listeners and the API call with promises: 首先,用promise封装套接字侦听器和API调用:

  const getUserId = new Promise(res => socket.on('get bot inv', res));
 const getBotId = new Promise(res => socket.on('get bot inv', res));

  function getInventory(id) {
    return new Promise((res, rej) => {
      Trade.getInventory(id, config.appID, config.contextID, (err, data) => {
        if(err) rej(err) else res(data);
    });
  }

Then its easy to chain the promises: 然后轻松实现承诺:

 (async function() {
   const userID = await getUserId;
   const data = await getInventory(userID);
   socket.emit({ data });

   const botID = await getBotId;
   const botData = await getInventory(config.bots[botID].steamID64);
   socket.emit({ botData });
 })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM