繁体   English   中英

如何在nodejs的for循环中使用.then或await?

[英]How to use .then or await inside a for loop in nodejs?

我有一个 Nodejs function,它注册一个事件以获取数据并进行一些操作,然后插入到弹性数据库中。 我的代码如下所示。

async function callB() {
    var block_reg = channel_event_hub.registerBlockEvent((block) => {
        const transactionArray = block.data.data;

        for (const trans of transactionArray) {
            var writeSet = trans.payload.data.actions[0]

            for (const writes of writeSet) {
                var updatefunc = validateVlaues(writeSet);

                updatefunc.then(function (result) {
                    EP.push(numberjson);
                    EP.push(result);
                })
            }
        }

        console.log("EP ", EP.length); // Executing even before .then

        elasticClient.bulk({
            index: 'indexdata',
            type: '_doc',
            body: EP,
        }
      }, (error) => {
    });
}

请帮我解决一下这个。 或者我如何在这种情况下使用await Function 是async function,但在Blockevent中我如何使用await 我坚持了很长时间。 有人可以建议我如何提前吗?

你在一个回调中。 您必须使回调async

async function callB() {
                                                   // here
 var block_reg = channel_event_hub.registerBlockEvent(async (block) => {
     const transactionArray = block.data.data;
     ...

然后你可以等待 Promise:

const result = await updatefunc;

只要 function 是异步 function 您就可以使用forfor..ofwhile等循环类型。

例如,如果您调用 function 从 api 读取数据,返回 Promise,您可以在循环中等待结果,一切都会如您所愿。

await 语法也比 .then 语法更易读,恕我直言。

 // function reading user details from https://jsonplaceholder.typicode.com/users async function getDataFromApi(userId) { return await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`).then(response => response.json()); } // Read results from all ids async function getAllDataFromApi() { let ids = [1,2,3]; for(let id of ids) { console.log(`Getting data from api for user id ${id}...`); let result = await getDataFromApi(id); console.log(`Result from api for user id ${id}:`, result); } } getAllDataFromApi();

暂无
暂无

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

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